package integration

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/common"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay"
	hlpayModels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay/models"
	hlpayServices "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay/services"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonpayModels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	photonpayServices "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/services"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	commonUtils "gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common/i18n"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

// HlPayAdapterHandler HlPay平台适配器处理器
type HlPayAdapterHandler struct {
	*BaseAdapter
	client *hlPay.HlPayClient
}

// NewHlPayAdapterHandler 创建HlPay适配器处理器
func NewHlPayAdapterHandler(platformID string, config *common.PlatformConfig, client *hlPay.HlPayClient) *HlPayAdapterHandler {
	return &HlPayAdapterHandler{
		BaseAdapter: NewBaseAdapter(platformID, config),
		client:      client,
	}
}

// HandleCardList 处理卡片列表查询
func (h *HlPayAdapterHandler) HandleCardList(ctx context.Context, req *common.CardListRequest) (*common.CardListResponse, error) {
	// 转换请求参数
	params := &hlpayModels.CardListRequest{
		CardNo: req.CardBin, // 使用CardBin作为CardNo
		Name:   "",          // 暂时为空
		Status: req.CardStatus,
	}

	// 调用HlPay服务
	result, err := hlpayServices.GetCardList(ctx, h.client, int(req.PageIndex), int(req.PageSize), params)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡片列表失败", err.Error())
	}

	// 直接返回PhotonPay格式的响应
	response := &common.CardListResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // HlPay成功码为0，转换为"0000"
			Msg:  "success",
		},
		PageIndex: req.PageIndex,
		PageSize:  req.PageSize,
		Total:     int64(result.Total),
	}

	// 将HlPay数据转换为PhotonPay格式
	if result.Rows != nil {
		// 获取所有卡片的ID
		cardIDs := make([]string, 0)
		for _, card := range result.Rows {
			if card.ID != "" {
				cardIDs = append(cardIDs, card.ID)
			}
		}

		// 从数据库中查询卡片昵称和总转账金额
		var cards []models.UserCard
		if err := database.DB.Where("card_id IN ?", cardIDs).Find(&cards).Error; err != nil {
			// 记录错误但继续处理
			fmt.Printf("[HlPay] 查询卡片昵称失败: %v\n", err)
		}

		// 创建卡片ID到昵称和总转账金额的映射
		type cardExtra struct {
			Nickname            string
			TotalTransferAmount decimal.Decimal
		}
		cardExtras := make(map[string]cardExtra)
		for _, card := range cards {
			cardExtras[card.CardID] = cardExtra{
				Nickname:            card.NikeName,
				TotalTransferAmount: card.TotalTransferAmount,
			}
		}

		response.Data = make([]common.CardInfo, len(result.Rows))
		for i, card := range result.Rows {
			// 解析余额
			balance, _ := strconv.ParseFloat(card.ActualBalance, 64)

			// 从数据库获取总转账金额
			transferAmount := 0.0
			if extra, exists := cardExtras[card.ID]; exists {
				transferAmount = extra.TotalTransferAmount.InexactFloat64()
			}

			// 获取卡BIN（从卡号前6位）
			cardBin := ""
			if len(card.CardNo) >= 6 {
				cardBin = card.CardNo[:6]
			}

			// 获取卡Scheme（根据BIN判断）
			cardScheme := ""
			if strings.HasPrefix(cardBin, "4") {
				cardScheme = "VISA"
			} else if strings.HasPrefix(cardBin, "5") {
				cardScheme = "MASTERCARD"
			}

			// 转换卡状态格式 - 使用统一状态映射
			cardStatus := commonUtils.MapPlatformStatusToUnified("hlpay", card.Status)

			// 获取昵称
			nickname := card.Nickname
			if extra, exists := cardExtras[card.ID]; exists && extra.Nickname != "" {
				nickname = extra.Nickname
			}

			response.Data[i] = common.CardInfo{
				CardBalance:         balance,
				CardCurrency:        "USD", // HlPay默认USD
				CardID:              card.ID,
				CardScheme:          cardScheme,
				CardStatus:          cardStatus,
				CardType:            "recharge", // HLpay默认常规卡recharge
				CreatedAt:           card.CreateTime,
				MatrixAccount:       req.MatrixAccount, // 使用请求中的matrixAccount
				MemberID:            "",                // HlPay没有会员ID概念
				MaskCardNo:          h.maskCardNo(card.CardNo),
				Nickname:            nickname,
				CardFormFactor:      "virtual_card", // HlPay默认虚拟卡
				TotalTransferAmount: transferAmount,
				TransactionLimit:    nil, // HlPay没有交易限额字段
			}
		}
	}

	return response, nil
}

// maskCardNo 掩码卡号
func (h *HlPayAdapterHandler) maskCardNo(cardNo string) string {
	if len(cardNo) <= 8 {
		return cardNo
	}
	return cardNo[:4] + "****" + cardNo[len(cardNo)-4:]
}

// HandleCardBinList 处理卡BIN列表查询
func (h *HlPayAdapterHandler) HandleCardBinList(ctx context.Context, req *common.CardBinListRequest) (*common.CardBinListResponse, error) {
	// 调用HlPay服务
	result, err := hlpayServices.GetCardBin(ctx, h.client)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡BIN列表失败", err.Error())
	}

	// 直接返回PhotonPay格式的响应
	// 创建一个包含原始数据的响应
	response := &common.CardBinListResponse{
		BaseResponse: common.BaseResponse{
			Code: result.Code,
			Msg:  string(result.Msg),
		},
		PageIndex: req.PageIndex,
		PageSize:  req.PageSize,
		Total:     int64(len(result.Data)),
	}

	// 将PhotonPay格式的数据转换为通用格式，但保持PhotonPay的字段结构
	if result.Data != nil {
		response.Data = make([]common.CardBinInfo, len(result.Data))
		for i, bin := range result.Data {
			response.Data[i] = common.CardBinInfo{
				CardBinId:     bin.CardBin, // 使用CardBin作为CardBinId
				Bin:           bin.CardBin,
				BinStatus:     "active",
				OpenCardFee:   "0",
				RechargeFee:   "0",
				RefundFee:     "0",
				TransFee:      nil,
				CancelFee:     "0",
				RefuseFee:     "0",
				AuthorizeFee:  "0",
				Remark:        "",
				MinCardAmount: 0,
				HasHot:        "N",
				HasNew:        "N",
				Network:       bin.CardScheme,
				Scene:         []string{"general"},
			}
		}
	}

	return response, nil
}

// HandleCardCVV 处理卡片CVV查询
func (h *HlPayAdapterHandler) HandleCardCVV(ctx context.Context, req *common.CardCVVRequest) (*common.CardCVVResponse, error) {
	// 调用HlPay的GetCardDetail服务获取卡片详情（包含CVV）
	result, err := hlpayServices.GetCardDetail(ctx, h.client, req.CardID)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡片详情失败", err.Error())
	}

	// 检查响应状态
	if result.Code != 200 {
		return nil, NewPlatformError(h.platformID, "API_ERROR", result.Msg, "CVV查询失败")
	}

	// 检查CVV是否为空
	if result.Data.CVV == "" {
		return nil, NewPlatformError(h.platformID, "CVV_NOT_FOUND", "CVV信息为空", "无法获取CVV信息")
	}

	// 返回CVV信息
	return &common.CardCVVResponse{
		BaseResponse: common.BaseResponse{
			Code: strconv.Itoa(result.Code),
			Msg:  result.Msg,
		},
		Data: common.CardCVVInfo{
			CardID: req.CardID,
			CVV:    result.Data.CVV,
		},
	}, nil
}

// HandleCardDetail 处理卡片详情查询
func (h *HlPayAdapterHandler) HandleCardDetail(ctx context.Context, req *common.CardDetailRequest) (*common.CardDetailResponse, error) {
	// 调用HlPay的GetCardDetail服务获取卡片详情
	result, err := hlpayServices.GetCardDetail(ctx, h.client, req.CardID)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡片详情失败", err.Error())
	}

	// 检查响应状态
	if result.Code != 200 {
		return nil, NewPlatformError(h.platformID, "API_ERROR", result.Msg, "获取卡片详情失败")
	}

	// 将HlPay数据转换为统一格式
	cardDetail := result.Data

	// 解析余额
	balance, _ := strconv.ParseFloat(cardDetail.ActualBalance, 64)

	// 获取卡BIN（从卡号前6位）
	cardBin := ""
	if len(cardDetail.CardNo) >= 6 {
		cardBin = cardDetail.CardNo[:6]
	}

	// 获取卡Scheme（根据BIN判断）
	cardScheme := ""
	if strings.HasPrefix(cardBin, "4") {
		cardScheme = "VISA"
	} else if strings.HasPrefix(cardBin, "5") {
		cardScheme = "MASTERCARD"
	}

	// 转换卡状态格式
	cardStatus := "NORMAL"
	switch strings.ToUpper(cardDetail.Status) {
	case "ACTIVE":
		cardStatus = "NORMAL"
	case "FROZEN":
		cardStatus = "FROZEN"
	case "CLOSED":
		cardStatus = "CLOSED"
	default:
		cardStatus = "NORMAL"
	}

	// 构建过期日期
	expirationDate := ""
	if cardDetail.ExpYear != "" && cardDetail.ExpMonth != "" {
		expirationDate = cardDetail.ExpMonth + "/" + cardDetail.ExpYear
	}

	// 构建手机号
	mobile := cardDetail.Phone
	mobilePrefix := ""
	if cardDetail.PhoneCode != nil {
		mobilePrefix = *cardDetail.PhoneCode
	}

	// 构建账单地址
	billingAddress := cardDetail.CardAddress
	if cardDetail.City != "" {
		if billingAddress != "" {
			billingAddress += ", "
		}
		billingAddress += cardDetail.City
	}
	if cardDetail.State != "" {
		if billingAddress != "" {
			billingAddress += ", "
		}
		billingAddress += cardDetail.State
	}

	// 从数据库获取总转账金额和昵称
	var userCard models.UserCard
	var totalTransferAmount float64
	var nickname string
	if err := database.DB.Where("card_id = ?", req.CardID).First(&userCard).Error; err == nil {
		totalTransferAmount = userCard.TotalTransferAmount.InexactFloat64()
		nickname = userCard.NikeName
	}

	response := &common.CardDetailResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // 转换为统一成功码
			Msg:  "success",
		},
		Data: common.CardDetailInfo{
			CardID:                  cardDetail.ID,
			CardNo:                  cardDetail.CardNo,
			MaskCardNo:              h.maskCardNo(cardDetail.CardNo),
			CardBin:                 cardBin,
			CardScheme:              cardScheme,
			CardType:                "recharge", // HlPay默认常规卡
			CardStatus:              cardStatus,
			CardBalance:             balance,
			CardCurrency:            "USD",          // HlPay默认USD
			CardFormFactor:          "virtual_card", // HlPay默认虚拟卡
			ExpirationDate:          expirationDate,
			CVV:                     cardDetail.CVV,
			FirstName:               cardDetail.FirstName,
			LastName:                cardDetail.LastName,
			Email:                   cardDetail.Email,
			Mobile:                  mobile,
			MobilePrefix:            mobilePrefix,
			BillingAddress:          billingAddress,
			BillingCity:             cardDetail.City,
			BillingState:            cardDetail.State,
			BillingPostalCode:       cardDetail.Zip,
			BillingCountry:          "US", // HlPay默认美国
			Nationality:             "US", // HlPay默认美国
			Nickname:                nickname,
			MatrixAccount:           "",  // HlPay没有矩阵账户概念
			MemberID:                "",  // HlPay没有会员ID概念
			CardholderID:            "",  // HlPay没有持卡人ID概念
			TransactionLimit:        nil, // HlPay没有交易限额字段
			TransactionLimitType:    "",  // HlPay没有交易限额类型字段
			BillingAddressUpdatable: "",  // HlPay没有账单地址可更新字段
			CreatedAt:               cardDetail.CreateTime,
			TotalTransferAmount:     totalTransferAmount,
		},
	}

	return response, nil
}

// HandleCardholderList 处理持卡人列表查询
func (h *HlPayAdapterHandler) HandleCardholderList(ctx context.Context, req *common.CardholderListRequest) (*common.CardholderListResponse, error) {
	// 获取全局数据库连接
	db := database.DB
	if db == nil {
		return nil, NewPlatformError(h.platformID, "DATABASE_ERROR", "数据库连接失败", "无法获取数据库连接")
	}

	// 创建持卡人服务
	cardholderService := hlpayServices.NewCardholderService(db)

	// 构建查询条件
	filters := make(map[string]interface{})

	// 添加矩阵账户过滤条件
	if req.MatrixAccount != "" {
		filters["matrix_account"] = req.MatrixAccount
	}

	// 从上下文中获取额外的查询参数
	if ctx.Value("cardholder_id") != nil {
		if cardholderID, ok := ctx.Value("cardholder_id").(string); ok && cardholderID != "" {
			filters["cardholder_id"] = cardholderID
		}
	}

	if ctx.Value("status") != nil {
		if status, ok := ctx.Value("status").(string); ok && status != "" {
			filters["status"] = status
		}
	}

	if ctx.Value("name") != nil {
		if name, ok := ctx.Value("name").(string); ok && name != "" {
			filters["name"] = name
		}
	}
	if ctx.Value("first_name") != nil {
		if firstName, ok := ctx.Value("first_name").(string); ok && firstName != "" {
			filters["first_name"] = firstName
		}
	}
	if ctx.Value("last_name") != nil {
		if lastName, ok := ctx.Value("last_name").(string); ok && lastName != "" {
			filters["last_name"] = lastName
		}
	}

	if ctx.Value("created_at_start") != nil {
		if createdAtStart, ok := ctx.Value("created_at_start").(string); ok && createdAtStart != "" {
			filters["created_at_start"] = createdAtStart
		}
	}

	if ctx.Value("created_at_end") != nil {
		if createdAtEnd, ok := ctx.Value("created_at_end").(string); ok && createdAtEnd != "" {
			filters["created_at_end"] = createdAtEnd
		}
	}

	// 调用持卡人服务
	cardholders, total, err := cardholderService.GetCardholderList(ctx, int(req.PageIndex), int(req.PageSize), filters)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取持卡人列表失败", err.Error())
	}

	// 构建响应
	response := &common.CardholderListResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		PageIndex: req.PageIndex,
		PageSize:  req.PageSize,
		Total:     total,
	}

	// 转换数据格式
	if cardholders != nil {
		response.Data = make([]common.CardholderInfo, len(cardholders))
		for i, cardholder := range cardholders {
			// 格式化出生日期
			dateOfBirth := ""
			if cardholder.DateOfBirth != nil {
				dateOfBirth = cardholder.DateOfBirth.Format("2006-01-02")
			}

			response.Data[i] = common.CardholderInfo{
				CardholderID:               strconv.FormatInt(cardholder.ID, 10),
				HlPayCardholderID:          cardholder.HlPayCardholderID,
				FirstName:                  cardholder.FirstName,
				LastName:                   cardholder.LastName,
				CardholderNameAbbreviation: cardholder.CardholderNameAbbreviation,
				Email:                      cardholder.Email,
				Mobile:                     cardholder.Mobile,
				MobilePrefix:               cardholder.MobilePrefix,
				DateOfBirth:                dateOfBirth,
				CertType:                   cardholder.CertType,
				Portrait:                   cardholder.Portrait,
				ReverseSide:                cardholder.ReverseSide,
				NationalityCountryCode:     cardholder.NationalityCountryCode,
				ResidentialAddress:         cardholder.ResidentialAddress,
				ResidentialCity:            cardholder.ResidentialCity,
				ResidentialCountryCode:     cardholder.ResidentialCountryCode,
				ResidentialPostalCode:      cardholder.ResidentialPostalCode,
				ResidentialState:           cardholder.ResidentialState,
				Status:                     cardholder.Status,
				CreatedAt:                  cardholder.CreatedAt.Format("2006-01-02T15:04:05"),
				MatrixAccount:              cardholder.MatrixAccount,
				MemberID:                   cardholder.MemberID,
				IsLegal:                    cardholder.IsLegal,
				CardholderReviewStatus:     cardholder.CardholderReviewStatus,
				Reason:                     cardholder.Reason,
			}
		}
	}

	return response, nil
}

// HandleCreateCardholder 处理创建持卡人
func (h *HlPayAdapterHandler) HandleCreateCardholder(ctx context.Context, req *common.CreateCardholderRequest) (*common.CreateCardholderResponse, error) {
	// 获取全局数据库连接
	db := database.DB
	if db == nil {
		return nil, NewPlatformError(h.platformID, "DATABASE_ERROR",
			i18n.Messages["database_connection_error"].CN,
			"无法获取数据库连接，请检查数据库配置")
	}

	// 从请求中获取用户ID
	userID := req.UserID
	if userID == 0 {
		return nil, NewPlatformError(h.platformID, "INVALID_PARAMETER",
			"用户ID不能为空",
			"无法获取用户ID，请确保请求中包含有效的用户ID")
	}

	// 从数据库获取用户的matrix_account信息
	var matrixAccount models.UserMatrixAccount
	if err := db.Where("user_id = ? AND status = 'active'", userID).First(&matrixAccount).Error; err != nil {
		return nil, NewPlatformError(h.platformID, "MATRIX_ACCOUNT_NOT_FOUND",
			i18n.Messages["matrix_account_not_found"].CN,
			"用户没有激活的矩阵账户，请先创建或激活矩阵账户")
	}

	// 创建持卡人服务
	cardholderService := hlpayServices.NewCardholderService(db)

	// 构建创建请求
	createReq := &hlpayModels.CreateHlPayCardholderRequest{
		UserID:                     userID,
		FirstName:                  req.FirstName,
		LastName:                   req.LastName,
		CardholderNameAbbreviation: req.CardholderNameAbbreviation,
		Email:                      req.Email,
		Mobile:                     req.Mobile,
		MobilePrefix:               req.MobilePrefix,
		DateOfBirth:                req.DateOfBirth,
		CertType:                   req.CertType,
		Portrait:                   req.Portrait,
		ReverseSide:                req.ReverseSide,
		NationalityCountryCode:     req.NationalityCountryCode,
		ResidentialAddress:         req.ResidentialAddress,
		ResidentialCity:            req.ResidentialCity,
		ResidentialCountryCode:     req.ResidentialCountryCode,
		ResidentialPostalCode:      req.ResidentialPostalCode,
		ResidentialState:           req.ResidentialState,
		MatrixAccount:              matrixAccount.MatrixAccount,
		MemberID:                   matrixAccount.MatrixAccount, // 使用matrix_account作为member_id
	}

	// 调用持卡人服务
	cardholder, err := cardholderService.CreateCardholder(ctx, createReq)
	if err != nil {
		// 提供更详细的错误信息
		errorMsg := err.Error()
		var errorCode, errorTitle, errorDetail string

		switch {
		case strings.Contains(errorMsg, "持卡人ID已存在"):
			errorCode = "DUPLICATE_CARDHOLDER_ID"
			errorTitle = "持卡人ID重复"
			errorDetail = "生成的持卡人ID已存在，请重试"
		case strings.Contains(errorMsg, "创建持卡人失败"):
			errorCode = "DATABASE_ERROR"
			errorTitle = i18n.Messages["database_connection_error"].CN
			errorDetail = "数据库操作失败，请检查数据库连接和表结构，或联系技术支持"
		case strings.Contains(errorMsg, "提交事务失败"):
			errorCode = "TRANSACTION_ERROR"
			errorTitle = i18n.Messages["transaction_error"].CN
			errorDetail = "数据库事务提交失败，请稍后重试或联系技术支持"
		default:
			errorCode = "API_CALL_ERROR"
			errorTitle = "创建持卡人失败"
			errorDetail = errorMsg
		}

		return nil, NewPlatformError(h.platformID, errorCode, errorTitle, errorDetail)
	}

	// 更新持卡人记录，绑定matrix_account
	if err := db.Model(&hlpayModels.HlPayCardholder{}).
		Where("id = ?", cardholder.ID).
		Updates(map[string]interface{}{
			"matrix_account": matrixAccount.MatrixAccount,
			"member_id":      matrixAccount.MatrixAccount, // 使用matrix_account作为member_id
		}).Error; err != nil {
		return nil, NewPlatformError(h.platformID, "UPDATE_MATRIX_ACCOUNT_FAILED",
			"绑定矩阵账户失败",
			"持卡人创建成功但绑定矩阵账户失败："+err.Error())
	}

	// 构建响应
	response := &common.CreateCardholderResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: gin.H{
			"cardholder_id":       strconv.FormatInt(cardholder.ID, 10),
			"hlpay_cardholder_id": cardholder.HlPayCardholderID,
			"matrix_account":      matrixAccount.MatrixAccount,
		},
	}

	return response, nil
}

// HandleUpdateCardholder 处理更新持卡人
func (h *HlPayAdapterHandler) HandleUpdateCardholder(ctx context.Context, req *common.UpdateCardholderRequest) (*common.UpdateCardholderResponse, error) {
	// 获取全局数据库连接
	db := database.DB
	if db == nil {
		return nil, NewPlatformError(h.platformID, "DATABASE_ERROR", "数据库连接失败", "无法获取数据库连接")
	}

	// 创建持卡人服务
	cardholderService := hlpayServices.NewCardholderService(db)

	// 根据hlpay_cardholder_id查找持卡人
	var cardholder hlpayModels.HlPayCardholder
	if err := db.Where("hlpay_cardholder_id = ?", req.CardholderID).First(&cardholder).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, NewPlatformError(h.platformID, "CARDHOLDER_NOT_FOUND", "持卡人不存在", fmt.Sprintf("无法找到持卡人ID: %s", req.CardholderID))
		}
		return nil, NewPlatformError(h.platformID, "DATABASE_ERROR", "查询持卡人失败", err.Error())
	}

	// 构建更新请求，补全所有字段
	updateReq := &hlpayModels.UpdateHlPayCardholderRequest{
		ID:                         cardholder.ID, // 使用数据库中的数字ID
		FirstName:                  req.FirstName,
		LastName:                   req.LastName,
		CardholderNameAbbreviation: req.CardholderNameAbbreviation,
		Email:                      req.Email,
		Mobile:                     req.Mobile,
		MobilePrefix:               req.MobilePrefix,
		DateOfBirth:                req.DateOfBirth,
		CertType:                   req.CertType,
		Portrait:                   req.Portrait,
		ReverseSide:                req.ReverseSide,
		NationalityCountryCode:     req.NationalityCountryCode,
		ResidentialAddress:         req.ResidentialAddress,
		ResidentialCity:            req.ResidentialCity,
		ResidentialCountryCode:     req.ResidentialCountryCode,
		ResidentialPostalCode:      req.ResidentialPostalCode,
		ResidentialState:           req.ResidentialState,
		Status:                     req.Status,
	}

	// 调用持卡人服务
	updatedCardholder, err := cardholderService.UpdateCardholder(ctx, updateReq)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "更新持卡人失败", err.Error())
	}

	// 构建响应，全部字段返回
	response := &common.UpdateCardholderResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: common.CardholderInfo{
			CardholderID:               req.CardholderID, // 返回前端传递的cardholderId
			HlPayCardholderID:          updatedCardholder.HlPayCardholderID,
			FirstName:                  updatedCardholder.FirstName,
			LastName:                   updatedCardholder.LastName,
			CardholderNameAbbreviation: updatedCardholder.CardholderNameAbbreviation,
			Email:                      updatedCardholder.Email,
			Mobile:                     updatedCardholder.Mobile,
			MobilePrefix:               updatedCardholder.MobilePrefix,
			DateOfBirth:                "",
			CertType:                   updatedCardholder.CertType,
			Portrait:                   updatedCardholder.Portrait,
			ReverseSide:                updatedCardholder.ReverseSide,
			NationalityCountryCode:     updatedCardholder.NationalityCountryCode,
			ResidentialAddress:         updatedCardholder.ResidentialAddress,
			ResidentialCity:            updatedCardholder.ResidentialCity,
			ResidentialCountryCode:     updatedCardholder.ResidentialCountryCode,
			ResidentialPostalCode:      updatedCardholder.ResidentialPostalCode,
			ResidentialState:           updatedCardholder.ResidentialState,
			Status:                     updatedCardholder.Status,
			CreatedAt:                  updatedCardholder.CreatedAt.Format("2006-01-02 15:04:05"),
			MatrixAccount:              updatedCardholder.MatrixAccount,
			MemberID:                   updatedCardholder.MemberID,
			IsLegal:                    updatedCardholder.IsLegal,
			CardholderReviewStatus:     updatedCardholder.CardholderReviewStatus,
			Reason:                     updatedCardholder.Reason,
		},
	}

	// 格式化出生日期
	if updatedCardholder.DateOfBirth != nil {
		response.Data.DateOfBirth = updatedCardholder.DateOfBirth.Format("2006-01-02")
	}

	return response, nil
}

// HandleCardHistoryList 处理卡历史列表查询
func (h *HlPayAdapterHandler) HandleCardHistoryList(ctx context.Context, req *common.CardHistoryListRequest) (*common.CardHistoryListResponse, error) {
	fmt.Printf("[HlPayAdapterHandler] 开始处理卡历史列表查询\n")

	// 构建HlPay查询参数
	params := hlpayModels.CardHistoryListRequest{
		PageIndex:      req.PageIndex,
		PageSize:       req.PageSize,
		CardID:         req.CardID,
		CardFormFactor: req.CardFormFactor,
		Status:         req.Status,
		FeeType:        req.FeeType,
		CreatedAtStart: req.CreatedAtStart,
		CreatedAtEnd:   req.CreatedAtEnd,
	}

	// 调用HlPay服务
	fmt.Printf("[HlPayAdapterHandler] 调用HlPay服务获取卡历史\n")
	result, err := hlpayServices.GetCardHistoryList(ctx, h.client, &params)
	if err != nil {
		fmt.Printf("[HlPayAdapterHandler] 错误：调用HlPay服务失败: %v\n", err)
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡片历史失败", err.Error())
	}
	fmt.Printf("[HlPayAdapterHandler] HlPay服务调用成功\n")

	// 转换为统一格式
	fmt.Printf("[HlPayAdapterHandler] 开始转换为统一格式\n")
	response := &common.CardHistoryListResponse{
		BaseResponse: common.BaseResponse{
			Code: result.Code,
			Msg:  result.Msg,
		},
		PageIndex: result.PageIndex,
		PageSize:  result.PageSize,
		Total:     result.Total,
	}

	// 转换历史信息
	if result.Data != nil {
		response.Data = make([]common.CardHistoryInfo, len(result.Data))
		for i, history := range result.Data {
			response.Data[i] = common.CardHistoryInfo{
				ActualFeeAmount:   history.ActualFeeAmount,
				ActualFeeCurrency: history.ActualFeeCurrency,
				CardID:            history.CardID,
				CardScheme:        history.CardScheme,
				CardType:          history.CardType,
				CreatedAt:         history.CreatedAt,
				FeeType:           history.FeeType,
				MaskCardNo:        history.MaskCardNo,
				MemberID:          history.MemberID,
				MatrixAccount:     history.MatrixAccount,
				Nickname:          history.Nickname,
				ReferenceNo:       history.ReferenceNo,
				Status:            history.Status,
				CardFormFactor:    history.CardFormFactor,
				CardNickname:      history.CardNickname,
			}
		}
	}

	return response, nil
}

// HandleOpenCard 处理开卡请求
func (h *HlPayAdapterHandler) HandleOpenCard(ctx context.Context, req *common.OpenCardRequest) (*common.OpenCardResponse, error) {
	// 获取数据库连接
	db := database.DB
	if db == nil {
		return nil, NewPlatformError(h.platformID, "DATABASE_ERROR", "数据库连接失败", "无法获取数据库连接")
	}

	// 根据 cardholderId 获取持卡人信息
	var cardholder hlpayModels.HlPayCardholder
	if err := db.Where("hlpay_cardholder_id = ?", req.CardholderID).First(&cardholder).Error; err != nil {
		return nil, NewPlatformError(h.platformID, "CARDHOLDER_NOT_FOUND", "持卡人不存在", fmt.Sprintf("无法找到持卡人ID: %s", req.CardholderID))
	}

	// 检查持卡人状态
	if cardholder.Status != "ACTIVE" {
		return nil, NewPlatformError(h.platformID, "CARDHOLDER_INACTIVE", "持卡人状态异常", fmt.Sprintf("持卡人状态为: %s", cardholder.Status))
	}

	// 验证持卡人信息
	if err := h.validateCardholderInfo(&cardholder); err != nil {
		return nil, NewPlatformError(h.platformID, "INVALID_CARDHOLDER_INFO", "持卡人信息无效", err.Error())
	}

	// 根据 AccountNo 获取账户信息
	var accountBalance models.HlPayAccountBalance
	accountNo := req.AccountNo
	if accountNo == "" {
		// 如果没有提供AccountNo，使用AccountID作为备选
		accountNo = req.AccountID
	}

	if err := db.Where("account_no = ?", accountNo).First(&accountBalance).Error; err != nil {
		return nil, NewPlatformError(h.platformID, "ACCOUNT_NOT_FOUND", "账户不存在", fmt.Sprintf("无法找到账户: %s", accountNo))
	}

	// 检查账户状态
	if accountBalance.Status != "active" {
		return nil, NewPlatformError(h.platformID, "ACCOUNT_INACTIVE", "账户状态异常", fmt.Sprintf("账户状态为: %s", accountBalance.Status))
	}

	// 开卡前检查余额是否足够
	if req.RechargeAmount != "" {
		rechargeAmount, _ := strconv.ParseFloat(req.RechargeAmount, 64)
		rechargeAmountDecimal := decimal.NewFromFloat(rechargeAmount)

		// 根据用户ID查询用户信息，获取role_id
		var user models.User
		if err := db.Where("id = ?", req.UserID).First(&user).Error; err != nil {
			fmt.Printf("[HLPay] 查询用户信息失败: %v\n", err)
			return nil, fmt.Errorf("用户不存在")
		}

		fmt.Printf("[HLPay] 用户ID: %d, 角色ID: %d\n", req.UserID, user.RoleID)

		// 根据用户角色检查相应的余额
		// 注意：暂时注释掉HlPay开卡的余额检查功能，因为接口延迟不准确
		// 之后会通过webhook回调来实现金额计算
		/*
			switch user.RoleID {
			case 2: // 普通用户 - 检查hlpay_account_balances表余额
				fmt.Printf("[HLPay] 普通用户开卡，检查hlpay_account_balances表余额\n")
				// 检查hlpay_account_balances表中的余额
				if accountBalance.RealTimeBalance.LessThan(rechargeAmountDecimal) {
					fmt.Printf("[HLPay] hlpay账户余额不足: %s < %s\n", accountBalance.RealTimeBalance.String(), rechargeAmountDecimal.String())
					return nil, fmt.Errorf("hlpay账户余额不足")
				}
				fmt.Printf("[HLPay] hlpay账户余额检查通过: %s >= %s\n", accountBalance.RealTimeBalance.String(), rechargeAmountDecimal.String())
			case 3: // 主账号 - 检查主账号表余额
				var masterAccount models.MasterAccount
				if err := db.Where("user_id = ?", req.UserID).First(&masterAccount).Error; err != nil {
					fmt.Printf("[HLPay] 检查主账号余额失败: 找不到主账号记录: %v\n", err)
					// 自动创建主账号记录
					fmt.Printf("[HLPay] 尝试为用户 %d 自动创建主账号记录\n", req.UserID)
					masterAccount = models.MasterAccount{
						UserID:         req.UserID,
						AccountName:    fmt.Sprintf("主账号_%d", req.UserID),
						AccountType:    "enterprise",
						Status:         "active",
						MaxSubAccounts: 10,
						Balance:        decimal.Zero, // 初始余额为0
					}
					if err := db.Create(&masterAccount).Error; err != nil {
						fmt.Printf("[HLPay] 自动创建主账号记录失败: %v\n", err)
						return nil, fmt.Errorf("主账号余额记录不存在且创建失败")
					}
					fmt.Printf("[HLPay] 成功为用户 %d 创建主账号记录，ID: %d\n", req.UserID, masterAccount.ID)
				}
				if masterAccount.Balance.LessThan(rechargeAmountDecimal) {
					fmt.Printf("[HLPay] 主账号余额不足: %s < %s\n", masterAccount.Balance.String(), rechargeAmountDecimal.String())
					return nil, fmt.Errorf("主账号余额不足")
				}
				fmt.Printf("[HLPay] 主账号余额检查通过: %s >= %s\n", masterAccount.Balance.String(), rechargeAmountDecimal.String())
			case 5: // 子账号 - 检查子账号表余额
				var subAccount models.SubAccount
				if err := db.Where("user_id = ?", req.UserID).First(&subAccount).Error; err != nil {
					fmt.Printf("[HLPay] 检查子账号余额失败: 找不到子账号记录: %v\n", err)
					return nil, fmt.Errorf("子账号余额记录不存在")
				}
				if subAccount.Balance.LessThan(rechargeAmountDecimal) {
					fmt.Printf("[HLPay] 子账号余额不足: %s < %s\n", subAccount.Balance.String(), rechargeAmountDecimal.String())
					return nil, fmt.Errorf("子账号余额不足")
				}
				fmt.Printf("[HLPay] 子账号余额检查通过: %s >= %s\n", subAccount.Balance.String(), rechargeAmountDecimal.String())
			default:
				// 对于其他角色，也尝试从主账号表检查余额（保持向后兼容）
				var masterAccount models.MasterAccount
				if err := db.Where("user_id = ?", req.UserID).First(&masterAccount).Error; err != nil {
					fmt.Printf("[HLPay] 检查账户余额失败: 找不到账户记录: %v\n", err)
					// 自动创建主账号记录
					fmt.Printf("[HLPay] 尝试为用户 %d 自动创建主账号记录\n", req.UserID)
					masterAccount = models.MasterAccount{
						UserID:         req.UserID,
						AccountName:    fmt.Sprintf("主账号_%d", req.UserID),
						AccountType:    "enterprise",
						Status:         "active",
						MaxSubAccounts: 10,
						Balance:        decimal.Zero, // 初始余额为0
					}
					if err := db.Create(&masterAccount).Error; err != nil {
						fmt.Printf("[HLPay] 自动创建主账号记录失败: %v\n", err)
						return nil, fmt.Errorf("账户余额记录不存在且创建失败")
					}
					fmt.Printf("[HLPay] 成功为用户 %d 创建主账号记录，ID: %d\n", req.UserID, masterAccount.ID)
				}
				if masterAccount.Balance.LessThan(rechargeAmountDecimal) {
					fmt.Printf("[HLPay] 账户余额不足: %s < %s\n", masterAccount.Balance.String(), rechargeAmountDecimal.String())
					return nil, fmt.Errorf("账户余额不足")
				}
				fmt.Printf("[HLPay] 账户余额检查通过: %s >= %s\n", masterAccount.Balance.String(), rechargeAmountDecimal.String())
			}
		*/

		// 临时日志：记录开卡但跳过余额检查
		fmt.Printf("[HLPay] 开卡但暂时跳过余额检查（将通过webhook回调处理）: 用户ID=%d, 角色ID=%d, 金额=%s\n",
			req.UserID, user.RoleID, rechargeAmountDecimal.String())
	}

	// 获取真实的CardBinId
	cardBinId := req.CardBin // 默认使用CardBin
	// 如果请求中直接提供了CardBinId，优先使用
	if req.CardBinId != "" {
		cardBinId = req.CardBinId
		fmt.Printf("[HLPay] 使用请求中的CardBinId: %s\n", cardBinId)
	} else {
		// 尝试从卡BIN查询中获取真实的CardBinId
		if realCardBinId, err := h.getCardBinIdFromBin(ctx, req.CardBin); err == nil {
			cardBinId = realCardBinId
			fmt.Printf("[HLPay] 找到真实CardBinId: %s (对应CardBin: %s)\n", realCardBinId, req.CardBin)
		} else {
			fmt.Printf("[HLPay] 未找到真实CardBinId，使用CardBin作为CardBinId: %s\n", req.CardBin)
		}
	}

	// 构建手机号（包含前缀）
	phone := cardholder.Mobile
	if cardholder.MobilePrefix != "" && cardholder.MobilePrefix != "86" {
		phone = cardholder.MobilePrefix + cardholder.Mobile
	}

	// 验证和清理姓名信息
	firstName := strings.TrimSpace(cardholder.FirstName)
	lastName := strings.TrimSpace(cardholder.LastName)

	// 检查姓名是否为空或无效
	if firstName == "" || firstName == "undefined" || firstName == "null" {
		return nil, NewPlatformError(h.platformID, "INVALID_FIRST_NAME", "持卡人姓名为空或无效", fmt.Sprintf("firstName: %s", firstName))
	}

	if lastName == "" || lastName == "undefined" || lastName == "null" {
		return nil, NewPlatformError(h.platformID, "INVALID_LAST_NAME", "持卡人姓名为空或无效", fmt.Sprintf("lastName: %s", lastName))
	}

	// 验证邮箱格式
	email := strings.TrimSpace(cardholder.Email)
	if email == "" || !strings.Contains(email, "@") {
		return nil, NewPlatformError(h.platformID, "INVALID_EMAIL", "持卡人邮箱格式无效", fmt.Sprintf("email: %s", email))
	}

	// 验证手机号
	if phone == "" || len(phone) < 10 {
		return nil, NewPlatformError(h.platformID, "INVALID_PHONE", "持卡人手机号无效", fmt.Sprintf("phone: %s", phone))
	}

	// 验证地址信息
	address := strings.TrimSpace(cardholder.ResidentialAddress)
	city := strings.TrimSpace(cardholder.ResidentialCity)
	state := strings.TrimSpace(cardholder.ResidentialState)
	zip := strings.TrimSpace(cardholder.ResidentialPostalCode)

	if address == "" {
		return nil, NewPlatformError(h.platformID, "INVALID_ADDRESS", "持卡人地址为空", "residentialAddress is required")
	}

	if city == "" {
		return nil, NewPlatformError(h.platformID, "INVALID_CITY", "持卡人城市为空", "residentialCity is required")
	}

	if state == "" {
		return nil, NewPlatformError(h.platformID, "INVALID_STATE", "持卡人州/省为空", "residentialState is required")
	}

	if zip == "" {
		return nil, NewPlatformError(h.platformID, "INVALID_ZIP", "持卡人邮编为空", "residentialPostalCode is required")
	}

	// 将通用开卡请求转换为HlPay格式
	hlpayRequest := &hlpayModels.OpenCardRequest{
		Bin:        req.CardBin,
		CardBinID:  cardBinId, // 使用获取到的CardBinId
		BatchCount: "1",       // HlPay使用字符串格式，默认开1张卡
		Cost:       0,         // HlPay的开卡费用，初始设为0
		// 添加持卡人信息
		FirstName: &firstName,
		LastName:  &lastName,
		Email:     &email,
		Phone:     &phone,
		// 添加地址信息
		CardAddress: &address,
		BillAddress: &address,
		City:        &city,
		State:       &state,
		Zip:         &zip,
	}

	// 设置Cost字段（这是卡片的初始金额）
	// 优先使用Cost字段，如果没有则使用RechargeAmount
	if req.Cost > 0 {
		hlpayRequest.Cost = req.Cost
		fmt.Printf("[HLPay] 使用Cost字段设置卡片初始金额: %f\n", req.Cost)
	} else if req.RechargeAmount != "" {
		fmt.Printf("[HLPay] 接收到RechargeAmount: %s\n", req.RechargeAmount)
		if cost, err := strconv.ParseFloat(req.RechargeAmount, 64); err == nil {
			hlpayRequest.Cost = cost
			fmt.Printf("[HLPay] 设置卡片初始金额 Cost: %f\n", cost)
		} else {
			fmt.Printf("[HLPay] 解析RechargeAmount失败: %v, 原始值: %s\n", err, req.RechargeAmount)
		}
	} else {
		fmt.Printf("[HLPay] 未接收到Cost或RechargeAmount字段\n")
	}

	// 添加调试信息
	fmt.Printf("[HLPay] 开卡请求参数:\n")
	fmt.Printf("  - CardBin: %s\n", req.CardBin)
	fmt.Printf("  - CardBinID: %s\n", hlpayRequest.CardBinID)
	fmt.Printf("  - CardholderID: %s\n", req.CardholderID)
	fmt.Printf("  - AccountNo: %s\n", accountNo)
	fmt.Printf("  - FirstName: %s (清理后)\n", firstName)
	fmt.Printf("  - LastName: %s (清理后)\n", lastName)
	fmt.Printf("  - Email: %s (清理后)\n", email)
	fmt.Printf("  - Phone: %s (清理后)\n", phone)
	fmt.Printf("  - Address: %s (清理后)\n", address)
	fmt.Printf("  - City: %s (清理后)\n", city)
	fmt.Printf("  - State: %s (清理后)\n", state)
	fmt.Printf("  - Zip: %s (清理后)\n", zip)
	fmt.Printf("  - Cost: %f\n", hlpayRequest.Cost)
	fmt.Printf("  - 原始请求Cost字段: %f\n", req.Cost)
	fmt.Printf("  - 原始请求RechargeAmount字段: %s\n", req.RechargeAmount)

	// 调用HlPay开卡服务
	result, err := hlpayServices.OpenCard(ctx, h.client, hlpayRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "开卡失败", err.Error())
	}

	// 检查响应状态
	if result.Code != 200 {
		return nil, NewPlatformError(h.platformID, "API_ERROR", result.Msg, "开卡失败")
	}

	// 开卡成功后，扣除数据库中的余额
	if req.RechargeAmount != "" {
		rechargeAmount, _ := strconv.ParseFloat(req.RechargeAmount, 64)
		rechargeAmountDecimal := decimal.NewFromFloat(rechargeAmount)

		// 根据用户ID查询用户信息，获取role_id
		var user models.User
		if err := db.Where("id = ?", req.UserID).First(&user).Error; err != nil {
			fmt.Printf("[HLPay] 查询用户信息失败: %v\n", err)
		} else {
			fmt.Printf("[HLPay] 用户ID: %d, 角色ID: %d\n", req.UserID, user.RoleID)

			// 根据用户角色扣除相应的余额
			// 注意：暂时注释掉HlPay开卡的余额扣除功能，因为接口延迟不准确
			// 之后会通过webhook回调来实现金额计算
			/*
				switch user.RoleID {
				case 2: // 普通用户 - 扣除hlpay_account_balances表余额
					fmt.Printf("[HLPay] 普通用户开卡，扣除hlpay_account_balances表余额\n")
					newBalance := accountBalance.RealTimeBalance.Sub(rechargeAmountDecimal)
					if err := db.Model(&accountBalance).Update("real_time_balance", newBalance).Error; err != nil {
						fmt.Printf("[HLPay] 更新hlpay账户余额失败: %v\n", err)
					} else {
						fmt.Printf("[HLPay] hlpay账户余额更新成功: %s -> %s\n", accountBalance.RealTimeBalance.String(), newBalance.String())
					}
				case 3: // 主账号 - 从主账号表扣除余额
					var masterAccount models.MasterAccount
					if err := db.Where("user_id = ?", req.UserID).First(&masterAccount).Error; err != nil {
						fmt.Printf("[HLPay] 更新主账号余额失败: 找不到主账号记录: %v\n", err)
					} else {
						if masterAccount.Balance.LessThan(rechargeAmountDecimal) {
							fmt.Printf("[HLPay] 主账号余额不足: %s < %s\n", masterAccount.Balance.String(), rechargeAmountDecimal.String())
						} else {
							newBalance := masterAccount.Balance.Sub(rechargeAmountDecimal)
							if err := db.Model(&masterAccount).Update("balance", newBalance).Error; err != nil {
								fmt.Printf("[HLPay] 更新主账号余额失败: %v\n", err)
							} else {
								fmt.Printf("[HLPay] 主账号余额更新成功: %s -> %s\n", masterAccount.Balance.String(), newBalance.String())
							}
						}
					}
				case 5: // 子账号 - 从子账号表扣除余额
					var subAccount models.SubAccount
					if err := db.Where("user_id = ?", req.UserID).First(&subAccount).Error; err != nil {
						fmt.Printf("[HLPay] 更新子账号余额失败: 找不到子账号记录: %v\n", err)
					} else {
						if subAccount.Balance.LessThan(rechargeAmountDecimal) {
							fmt.Printf("[HLPay] 子账号余额不足: %s < %s\n", subAccount.Balance.String(), rechargeAmountDecimal.String())
						} else {
							newBalance := subAccount.Balance.Sub(rechargeAmountDecimal)
							if err := db.Model(&subAccount).Update("balance", newBalance).Error; err != nil {
								fmt.Printf("[HLPay] 更新子账号余额失败: %v\n", err)
							} else {
								fmt.Printf("[HLPay] 子账号余额更新成功: %s -> %s\n", subAccount.Balance.String(), newBalance.String())
							}
						}
					}
				default:
					// 对于其他角色，也尝试从主账号表扣除余额（保持向后兼容）
					var masterAccount models.MasterAccount
					if err := db.Where("user_id = ?", req.UserID).First(&masterAccount).Error; err != nil {
						fmt.Printf("[HLPay] 更新账户余额失败: 找不到账户记录: %v\n", err)
					} else {
						if masterAccount.Balance.LessThan(rechargeAmountDecimal) {
							fmt.Printf("[HLPay] 账户余额不足: %s < %s\n", masterAccount.Balance.String(), rechargeAmountDecimal.String())
						} else {
							newBalance := masterAccount.Balance.Sub(rechargeAmountDecimal)
							if err := db.Model(&masterAccount).Update("balance", newBalance).Error; err != nil {
								fmt.Printf("[HLPay] 更新账户余额失败: %v\n", err)
							} else {
								fmt.Printf("[HLPay] 账户余额更新成功: %s -> %s\n", masterAccount.Balance.String(), newBalance.String())
							}
						}
					}
				}
			*/

			// 临时日志：记录开卡成功但跳过余额扣除
			fmt.Printf("[HLPay] 开卡成功，但暂时跳过余额扣除（将通过webhook回调处理）: 用户ID=%d, 角色ID=%d, 金额=%s\n",
				req.UserID, user.RoleID, rechargeAmountDecimal.String())
		}
	}

	// 返回统一格式的响应
	response := &common.OpenCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // HlPay成功码为200，转换为"0000"
			Msg:  "success",
		},
		Data: result.Data, // HlPay返回的是卡片ID字符串
	}

	fmt.Printf("[HLPay] 开卡成功，卡片ID: %s\n", result.Data)

	return response, nil
}

// HandleBatchOpenCard 处理批量开卡请求
func (h *HlPayAdapterHandler) HandleBatchOpenCard(ctx context.Context, req *common.BatchOpenCardRequest) (*common.BatchOpenCardResponse, error) {
	// 获取数据库连接
	db := database.DB
	if db == nil {
		return nil, NewPlatformError(h.platformID, "DATABASE_ERROR", "数据库连接失败", "无法获取数据库连接")
	}

	// 根据 cardholderId 获取持卡人信息
	var cardholder hlpayModels.HlPayCardholder
	if err := db.Where("hlpay_cardholder_id = ?", req.CardholderID).First(&cardholder).Error; err != nil {
		return nil, NewPlatformError(h.platformID, "CARDHOLDER_NOT_FOUND", "持卡人不存在", fmt.Sprintf("无法找到持卡人ID: %s", req.CardholderID))
	}

	// 检查持卡人状态
	if cardholder.Status != "ACTIVE" {
		return nil, NewPlatformError(h.platformID, "CARDHOLDER_INACTIVE", "持卡人状态异常", fmt.Sprintf("持卡人状态为: %s", cardholder.Status))
	}

	// 验证持卡人信息
	if err := h.validateCardholderInfo(&cardholder); err != nil {
		return nil, NewPlatformError(h.platformID, "INVALID_CARDHOLDER_INFO", "持卡人信息无效", err.Error())
	}

	// 根据 AccountNo 获取账户信息
	var accountBalance models.HlPayAccountBalance
	accountNo := req.AccountNo
	if accountNo == "" {
		// 如果没有提供AccountNo，使用AccountID作为备选
		accountNo = req.AccountID
	}

	if err := db.Where("account_no = ?", accountNo).First(&accountBalance).Error; err != nil {
		return nil, NewPlatformError(h.platformID, "ACCOUNT_NOT_FOUND", "账户不存在", fmt.Sprintf("无法找到账户: %s", accountNo))
	}

	// 检查账户状态
	if accountBalance.Status != "active" {
		return nil, NewPlatformError(h.platformID, "ACCOUNT_INACTIVE", "账户状态异常", fmt.Sprintf("账户状态为: %s", accountBalance.Status))
	}

	// 构建HlPay批量开卡请求
	hlpayRequest := &hlpayModels.BatchOpenCardRequest{
		CardAddress: req.CardAddress,
		Zip:         req.Zip,
		LastName:    req.LastName,
		Cost:        req.Cost,
		City:        req.City,
		Bin:         req.Bin,
		BatchCount:  req.BatchCount,
		FirstName:   req.FirstName,
		BillAddress: req.BillAddress,
		CardBinID:   req.CardBinId,
		Phone:       req.Phone,
		State:       req.State,
		Email:       req.Email,
	}

	// 调用HlPay批量开卡服务
	result, err := hlpayServices.BatchOpenCards(ctx, h.client, hlpayRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "批量开卡失败", err.Error())
	}

	// 检查响应状态
	if result.Code != 200 {
		return nil, NewPlatformError(h.platformID, "API_ERROR", result.Msg, "批量开卡失败")
	}

	// 返回统一格式的响应
	response := &common.BatchOpenCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // HlPay成功码为200，转换为"0000"
			Msg:  "success",
		},
		Data: result.Data, // HlPay返回的是批量任务ID字符串
	}

	fmt.Printf("[HLPay] 批量开卡成功，任务ID: %s\n", result.Data)

	return response, nil
}

// HandleRechargeCard 处理卡片充值请求
func (h *HlPayAdapterHandler) HandleRechargeCard(ctx context.Context, req *common.RechargeCardRequest) (*common.RechargeCardResponse, error) {
	// 获取数据库连接
	db := database.DB
	if db == nil {
		return nil, NewPlatformError(h.platformID, "DATABASE_ERROR", "数据库连接失败", "无法获取数据库连接")
	}

	// 从上下文中获取用户信息
	userID, exists := ctx.Value("user_id").(int64)
	if !exists {
		return nil, NewPlatformError(h.platformID, "USER_NOT_FOUND", "用户信息不存在", "无法从上下文中获取用户ID")
	}

	// 从上下文中获取矩阵账户信息
	matrixAccountInfo, exists := ctx.Value("matrix_account_info").(*models.UserMatrixAccount)
	if !exists {
		return nil, NewPlatformError(h.platformID, "MATRIX_ACCOUNT_NOT_FOUND", "矩阵账户信息不存在", "无法从上下文中获取矩阵账户信息")
	}

	// 检查余额 - 从hlpay_account_balances表中查找对应的账户余额
	var accountBalance models.HlPayAccountBalance
	if err := db.Where("owner_no = ? AND currency = ?", matrixAccountInfo.MatrixAccount, "USD").First(&accountBalance).Error; err != nil {
		return nil, NewPlatformError(h.platformID, "ACCOUNT_NOT_FOUND", "账户不存在", fmt.Sprintf("无法找到矩阵账户 %s 的USD余额记录", matrixAccountInfo.MatrixAccount))
	}

	// 检查账户状态
	if accountBalance.Status != "active" {
		return nil, NewPlatformError(h.platformID, "ACCOUNT_INACTIVE", "账户状态异常", fmt.Sprintf("账户状态为: %s", accountBalance.Status))
	}

	// 检查余额是否足够
	rechargeAmountDecimal := decimal.NewFromFloat(req.Amount)
	if accountBalance.RealTimeBalance.LessThan(rechargeAmountDecimal) {
		return nil, NewPlatformError(h.platformID, "INSUFFICIENT_BALANCE", "余额不足", fmt.Sprintf("账户余额 %s 小于充值金额 %s", accountBalance.RealTimeBalance.String(), rechargeAmountDecimal.String()))
	}

	// 将通用充值请求转换为HlPay格式
	hlpayRequest := &hlpayModels.RechargeRequest{
		ID:     req.CardID,
		Amount: req.Amount,
		Remark: req.Remark,
	}

	// 调用HlPay充值服务
	result, err := hlpayServices.Recharge(ctx, h.client, hlpayRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "充值失败", err.Error())
	}

	// 检查响应状态
	if result.Code != 200 {
		return nil, NewPlatformError(h.platformID, "API_ERROR", result.Msg, "充值失败")
	}

	// 充值成功后，扣除本地数据库中的余额
	// 使用事务确保数据一致性
	tx := db.Begin()
	if tx.Error != nil {
		return nil, NewPlatformError(h.platformID, "TRANSACTION_ERROR", "事务启动失败", tx.Error.Error())
	}

	// 扣除余额
	newBalance := accountBalance.RealTimeBalance.Sub(rechargeAmountDecimal)
	if err := tx.Model(&accountBalance).Update("real_time_balance", newBalance).Error; err != nil {
		tx.Rollback()
		return nil, NewPlatformError(h.platformID, "BALANCE_UPDATE_ERROR", "余额更新失败", err.Error())
	}

	// 更新卡片的TotalTransferAmount
	var userCard models.UserCard
	if err := tx.Where("card_id = ? AND user_id = ?", req.CardID, userID).First(&userCard).Error; err == nil {
		// 累加充值金额到现有的TotalTransferAmount
		newTotalTransferAmount := userCard.TotalTransferAmount.Add(rechargeAmountDecimal)
		if err := tx.Model(&userCard).Update("TotalTransferAmount", newTotalTransferAmount).Error; err != nil {
			tx.Rollback()
			return nil, NewPlatformError(h.platformID, "CARD_UPDATE_ERROR", "卡片信息更新失败", err.Error())
		}
		fmt.Printf("[HLPay] 更新卡片TotalTransferAmount成功: CardID=%s, 新增充值金额=%s, 总金额=%s\n",
			req.CardID, rechargeAmountDecimal.String(), newTotalTransferAmount.String())
	} else {
		fmt.Printf("[HLPay] 找不到卡片记录: CardID=%s, UserID=%d\n", req.CardID, userID)
		// 卡片记录不存在不影响充值，继续执行
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return nil, NewPlatformError(h.platformID, "TRANSACTION_COMMIT_ERROR", "事务提交失败", err.Error())
	}

	fmt.Printf("[HLPay] 充值成功并扣除余额: CardID=%s, 充值金额=%s, 账户余额从 %s 更新为 %s\n",
		req.CardID, rechargeAmountDecimal.String(), accountBalance.RealTimeBalance.String(), newBalance.String())

	// 返回统一格式的响应
	response := &common.RechargeCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // HlPay成功码为200，转换为"0000"
			Msg:  "success",
		},
		Data: result.Data,
	}

	return response, nil
}

// HandleWithdrawCard 处理卡片提现请求
func (h *HlPayAdapterHandler) HandleWithdrawCard(ctx context.Context, req *common.WithdrawCardRequest) (*common.WithdrawCardResponse, error) {
	// 获取数据库连接
	db := database.DB
	if db == nil {
		return nil, NewPlatformError(h.platformID, "DATABASE_ERROR", "数据库连接失败", "无法获取数据库连接")
	}

	// 从上下文中获取用户信息
	userID, exists := ctx.Value("user_id").(int64)
	if !exists {
		return nil, NewPlatformError(h.platformID, "USER_NOT_FOUND", "用户信息不存在", "无法从上下文中获取用户ID")
	}

	// 从上下文中获取矩阵账户信息
	matrixAccountInfo, exists := ctx.Value("matrix_account_info").(*models.UserMatrixAccount)
	if !exists {
		return nil, NewPlatformError(h.platformID, "MATRIX_ACCOUNT_NOT_FOUND", "矩阵账户信息不存在", "无法从上下文中获取矩阵账户信息")
	}

	// 检查余额 - 从hlpay_account_balances表中查找对应的账户余额
	var accountBalance models.HlPayAccountBalance
	if err := db.Where("owner_no = ? AND currency = ?", matrixAccountInfo.MatrixAccount, "USD").First(&accountBalance).Error; err != nil {
		return nil, NewPlatformError(h.platformID, "ACCOUNT_NOT_FOUND", "账户不存在", fmt.Sprintf("无法找到矩阵账户 %s 的USD余额记录", matrixAccountInfo.MatrixAccount))
	}

	// 检查账户状态
	if accountBalance.Status != "active" {
		return nil, NewPlatformError(h.platformID, "ACCOUNT_INACTIVE", "账户状态异常", fmt.Sprintf("账户状态为: %s", accountBalance.Status))
	}

	// 将通用提现请求转换为HlPay格式
	hlpayRequest := &hlpayModels.WithdrawRequest{
		ID:     req.CardID,
		Amount: req.Amount,
		Remark: req.Remark,
	}

	// 调用HlPay提现服务
	result, err := hlpayServices.Withdraw(ctx, h.client, hlpayRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "提现失败", err.Error())
	}

	// 检查响应状态
	if result.Code != 200 {
		return nil, NewPlatformError(h.platformID, "API_ERROR", result.Msg, "提现失败")
	}

	// 提现成功后，增加本地数据库中的余额
	// 使用事务确保数据一致性
	tx := db.Begin()
	if tx.Error != nil {
		return nil, NewPlatformError(h.platformID, "TRANSACTION_ERROR", "事务启动失败", tx.Error.Error())
	}

	// 增加余额
	withdrawAmountDecimal := decimal.NewFromFloat(req.Amount)
	newBalance := accountBalance.RealTimeBalance.Add(withdrawAmountDecimal)
	if err := tx.Model(&accountBalance).Update("real_time_balance", newBalance).Error; err != nil {
		tx.Rollback()
		return nil, NewPlatformError(h.platformID, "BALANCE_UPDATE_ERROR", "余额更新失败", err.Error())
	}

	// 更新卡片的TotalTransferAmount（减少，因为提现）
	var userCard models.UserCard
	if err := tx.Where("card_id = ? AND user_id = ?", req.CardID, userID).First(&userCard).Error; err == nil {
		// 减少提现金额从现有的TotalTransferAmount
		newTotalTransferAmount := userCard.TotalTransferAmount.Sub(withdrawAmountDecimal)
		if err := tx.Model(&userCard).Update("TotalTransferAmount", newTotalTransferAmount).Error; err != nil {
			tx.Rollback()
			return nil, NewPlatformError(h.platformID, "CARD_UPDATE_ERROR", "卡片信息更新失败", err.Error())
		}
		fmt.Printf("[HLPay] 更新卡片TotalTransferAmount成功: CardID=%s, 提现金额=%s, 总金额=%s\n",
			req.CardID, withdrawAmountDecimal.String(), newTotalTransferAmount.String())
	} else {
		fmt.Printf("[HLPay] 找不到卡片记录: CardID=%s, UserID=%d\n", req.CardID, userID)
		// 卡片记录不存在不影响提现，继续执行
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return nil, NewPlatformError(h.platformID, "TRANSACTION_COMMIT_ERROR", "事务提交失败", err.Error())
	}

	fmt.Printf("[HLPay] 提现成功并增加余额: CardID=%s, 提现金额=%s, 账户余额从 %s 更新为 %s\n",
		req.CardID, withdrawAmountDecimal.String(), accountBalance.RealTimeBalance.String(), newBalance.String())

	// 返回统一格式的响应
	response := &common.WithdrawCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // HlPay成功码为200，转换为"0000"
			Msg:  "success",
		},
		Data: result.Data,
	}

	return response, nil
}

// HandleFreezeCard 处理卡片冻结请求
func (h *HlPayAdapterHandler) HandleFreezeCard(ctx context.Context, req *common.FreezeCardRequest) (*common.FreezeCardResponse, error) {
	// 调用HlPay冻结服务
	result, err := hlpayServices.FreezeCard(ctx, h.client, req.CardID)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "冻结卡片失败", err.Error())
	}

	// 检查响应状态
	if result.Code != 200 {
		return nil, NewPlatformError(h.platformID, "API_ERROR", result.Msg, "冻结卡片失败")
	}

	// 返回统一格式的响应
	response := &common.FreezeCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // HlPay成功码为200，转换为"0000"
			Msg:  "success",
		},
		Data: result.Data,
	}

	return response, nil
}

// HandleEnableCard 处理卡片解冻请求
func (h *HlPayAdapterHandler) HandleEnableCard(ctx context.Context, req *common.EnableCardRequest) (*common.EnableCardResponse, error) {
	// 调用HlPay解冻服务
	result, err := hlpayServices.EnableCard(ctx, h.client, req.CardID)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "解冻卡片失败", err.Error())
	}

	// 检查响应状态
	if result.Code != 200 {
		return nil, NewPlatformError(h.platformID, "API_ERROR", result.Msg, "解冻卡片失败")
	}

	// 返回统一格式的响应
	response := &common.EnableCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // HlPay成功码为200，转换为"0000"
			Msg:  "success",
		},
		Data: result.Data,
	}

	return response, nil
}

// HandleCancelCard 处理卡片注销请求
func (h *HlPayAdapterHandler) HandleCancelCard(ctx context.Context, req *common.CancelCardRequest) (*common.CancelCardResponse, error) {
	// 调用HlPay注销服务
	result, err := hlpayServices.CancelCard(ctx, h.client, req.CardID)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "注销卡片失败", err.Error())
	}

	// 检查响应状态
	if result.Code != 200 {
		return nil, NewPlatformError(h.platformID, "API_ERROR", result.Msg, "注销卡片失败")
	}

	// 返回统一格式的响应
	response := &common.CancelCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // HlPay成功码为200，转换为"0000"
			Msg:  "success",
		},
		Data: result.Data,
	}

	return response, nil
}

// validateCardholderInfo 验证持卡人信息
func (h *HlPayAdapterHandler) validateCardholderInfo(cardholder *hlpayModels.HlPayCardholder) error {
	// 验证姓名
	firstName := strings.TrimSpace(cardholder.FirstName)
	lastName := strings.TrimSpace(cardholder.LastName)

	if firstName == "" || firstName == "undefined" || firstName == "null" {
		return fmt.Errorf("持卡人姓名为空或无效: %s", firstName)
	}

	if lastName == "" || lastName == "undefined" || lastName == "null" {
		return fmt.Errorf("持卡人姓名为空或无效: %s", lastName)
	}

	// 验证邮箱
	email := strings.TrimSpace(cardholder.Email)
	if email == "" || !strings.Contains(email, "@") {
		return fmt.Errorf("持卡人邮箱格式无效: %s", email)
	}

	// 验证手机号
	mobile := strings.TrimSpace(cardholder.Mobile)
	if mobile == "" || len(mobile) < 10 {
		return fmt.Errorf("持卡人手机号无效: %s", mobile)
	}

	// 验证地址信息
	address := strings.TrimSpace(cardholder.ResidentialAddress)
	city := strings.TrimSpace(cardholder.ResidentialCity)
	state := strings.TrimSpace(cardholder.ResidentialState)
	zip := strings.TrimSpace(cardholder.ResidentialPostalCode)

	if address == "" {
		return fmt.Errorf("持卡人地址为空")
	}
	if city == "" {
		return fmt.Errorf("持卡人城市为空")
	}
	if state == "" {
		return fmt.Errorf("持卡人州/省为空")
	}
	if zip == "" {
		return fmt.Errorf("持卡人邮编为空")
	}

	return nil
}

// getCardBinIdFromBin 从卡BIN查询中获取真实的CardBinId
func (h *HlPayAdapterHandler) getCardBinIdFromBin(ctx context.Context, cardBin string) (string, error) {
	// 调用HlPay的卡BIN查询服务
	result, err := hlpayServices.GetCardBin(ctx, h.client)
	if err != nil {
		return "", fmt.Errorf("获取卡BIN列表失败: %v", err)
	}

	// 在卡BIN列表中查找匹配的CardBinId
	for _, bin := range result.Data {
		if bin.CardBin == cardBin {
			return bin.CardBin, nil
		}
	}

	return "", fmt.Errorf("未找到对应的CardBinId")
}

// HandleTransactionList 处理交易列表查询请求
func (h *HlPayAdapterHandler) HandleTransactionList(ctx context.Context, req *common.TransactionListRequest) (*common.TransactionListResponse, error) {
	// 构建HlPay查询参数
	params := &hlpayModels.CardTransactionDetailRequest{
		CardId:          req.CardID,
		CardNo:          req.CardNo,
		Status:          req.Status,
		TransactionType: req.TransactionType,
		BeginTime:       req.BeginTime,
		EndTime:         req.EndTime,
	}

	// 调用HlPay交易查询服务
	response, err := hlpayServices.GetCardTransactionDetail(ctx, h.client, params)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取交易列表失败", err.Error())
	}

	// 转换为统一格式
	transactions := make([]common.TransactionInfo, 0, len(response.Rows))
	for _, row := range response.Rows {
		// 解析金额
		amount, _ := strconv.ParseFloat(row.Amount, 64)
		transactionAmount := 0.0
		if row.TransactionAmount != nil {
			transactionAmount, _ = strconv.ParseFloat(*row.TransactionAmount, 64)
		}
		fee, _ := strconv.ParseFloat(row.Fee, 64)

		// 获取交易详情
		detail := ""
		if row.Detail != nil {
			detail = *row.Detail
		}

		// 获取交易货币
		transactionCurrency := ""
		if row.TransactionCurrency != nil {
			transactionCurrency = *row.TransactionCurrency
		}

		transaction := common.TransactionInfo{
			TransactionID:       fmt.Sprintf("%v", row.ID),
			CardID:              row.CardId,
			CardNo:              row.CardNo,
			TransactionType:     row.TransactionType,
			Currency:            row.Currency,
			Amount:              amount,
			TransactionAmount:   transactionAmount,
			TransactionCurrency: transactionCurrency,
			Fee:                 fee,
			Status:              row.Status,
			TransactionTime:     row.TransactionTime,
			Detail:              detail,
			Remark:              row.Remark,
			CreateTime:          row.CreateTime,
		}

		transactions = append(transactions, transaction)
	}

	// 返回统一格式的响应
	transactionResponse := &common.TransactionListResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data:      transactions,
		PageIndex: 1, // HlPay不支持分页，默认为第1页
		PageSize:  int64(len(transactions)),
		Total:     int64(response.Total),
	}

	return transactionResponse, nil
}

// HandleTransactionDetail 处理交易详情查询请求
func (h *HlPayAdapterHandler) HandleTransactionDetail(ctx context.Context, req *common.TransactionDetailRequest) (*common.TransactionDetailResponse, error) {
	// HlPay不支持通过交易ID查询单个交易详情
	// 这里返回错误，建议使用交易列表查询
	return nil, NewPlatformError(h.platformID, "NOT_SUPPORTED", "HlPay不支持通过交易ID查询单个交易详情", "请使用交易列表查询接口")
}

// PhotonPayAdapterHandler PhotonPay平台适配器处理器
type PhotonPayAdapterHandler struct {
	*BaseAdapter
	client *photonpay.PhotonPayClient
}

// NewPhotonPayAdapterHandler 创建PhotonPay适配器处理器
func NewPhotonPayAdapterHandler(platformID string, config *common.PlatformConfig, client *photonpay.PhotonPayClient) *PhotonPayAdapterHandler {
	return &PhotonPayAdapterHandler{
		BaseAdapter: NewBaseAdapter(platformID, config),
		client:      client,
	}
}

// HandleCardList 处理卡片列表查询
func (h *PhotonPayAdapterHandler) HandleCardList(ctx context.Context, req *common.CardListRequest) (*common.CardListResponse, error) {
	// 转换请求参数
	params := photonpayModels.CardListQueryParams{
		PageIndex:      int(req.PageIndex),
		PageSize:       int(req.PageSize),
		MatrixAccount:  req.MatrixAccount,
		CardBin:        req.CardBin,
		CreatedAtStart: req.CreatedAtStart,
		CreatedAtEnd:   req.CreatedAtEnd,
		CardType:       req.CardType,
		CardFormFactor: req.CardFormFactor,
		CardStatus:     req.CardStatus,
	}

	// 调用PhotonPay服务
	result, err := photonpayServices.GetCardList(ctx, h.client, params)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡片列表失败", err.Error())
	}

	// 直接返回PhotonPay的原始响应格式
	response := &common.CardListResponse{
		BaseResponse: common.BaseResponse{
			Code: result.Code,
			Msg:  string(result.Msg),
		},
		PageIndex: result.PageIndex,
		PageSize:  result.PageSize,
		Total:     result.Total,
	}

	// 将PhotonPay的原始数据转换为通用格式，但保持PhotonPay的字段结构
	if result.Data != nil {
		response.Data = make([]common.CardInfo, len(result.Data))
		for i, card := range result.Data {
			response.Data[i] = common.CardInfo{
				CardBalance:         card.CardBalance,
				CardCurrency:        card.CardCurrency,
				CardID:              card.CardID,
				CardScheme:          card.CardScheme,
				CardStatus:          card.CardStatus,
				CardType:            card.CardType,
				CreatedAt:           card.CreatedAt,
				MatrixAccount:       card.MatrixAccount,
				MemberID:            card.MemberID,
				MaskCardNo:          card.MaskCardNo,
				Nickname:            card.Nickname,
				CardFormFactor:      card.CardFormFactor,
				TotalTransferAmount: card.TotalTransferAmount,
				TransactionLimit:    card.TransactionLimit,
			}
		}
	}

	return response, nil
}

// HandleCardBinList 处理卡BIN列表查询
func (h *PhotonPayAdapterHandler) HandleCardBinList(ctx context.Context, req *common.CardBinListRequest) (*common.CardBinListResponse, error) {
	// 转换请求参数
	params := photonpayModels.CardBinQueryParams{
		// PhotonPay的CardBinQueryParams没有分页字段，使用默认值
	}

	// 调用PhotonPay服务
	result, err := photonpayServices.GetCardBin(ctx, h.client, params)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡BIN列表失败", err.Error())
	}

	// 直接返回PhotonPay的原始响应格式
	// 创建一个包含原始数据的响应
	response := &common.CardBinListResponse{
		BaseResponse: common.BaseResponse{
			Code: result.Code,
			Msg:  string(result.Msg),
		},
		PageIndex: req.PageIndex,
		PageSize:  req.PageSize,
		Total:     int64(len(result.Data)),
	}

	// 将PhotonPay的原始数据转换为通用格式，但保持原始字段结构
	if result.Data != nil {
		response.Data = make([]common.CardBinInfo, len(result.Data))
		for i, bin := range result.Data {
			response.Data[i] = common.CardBinInfo{
				CardBinId:     bin.CardBin, // 使用CardBin作为CardBinId
				Bin:           bin.CardBin,
				BinStatus:     "active",
				OpenCardFee:   "0",
				RechargeFee:   "0",
				RefundFee:     "0",
				TransFee:      nil,
				CancelFee:     "0",
				RefuseFee:     "0",
				AuthorizeFee:  "0",
				Remark:        "",
				MinCardAmount: 0,
				HasHot:        "N",
				HasNew:        "N",
				Network:       bin.CardScheme,
				Scene:         []string{"general"},
			}
		}
	}

	return response, nil
}

// HandleCardCVV 处理卡片CVV查询
func (h *PhotonPayAdapterHandler) HandleCardCVV(ctx context.Context, req *common.CardCVVRequest) (*common.CardCVVResponse, error) {
	// 调用PhotonPay服务获取CVV
	result, err := photonpayServices.GetCardCVV(ctx, h.client, req.CardID)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡片CVV失败", err.Error())
	}

	// 解析PhotonPay的CVV响应
	var cvvResponse photonpayModels.CVVResponse

	// 解析JSON响应
	if err := json.Unmarshal(result, &cvvResponse); err != nil {
		return nil, NewPlatformError(h.platformID, "RESPONSE_PARSE_ERROR", "解析CVV响应失败", err.Error())
	}

	// 检查响应状态
	if cvvResponse.Code != "0000" {
		return nil, NewPlatformError(h.platformID, "API_ERROR", cvvResponse.GetMessage(), "获取CVV失败")
	}

	// 返回CVV信息
	return &common.CardCVVResponse{
		BaseResponse: common.BaseResponse{
			Code: cvvResponse.Code,
			Msg:  cvvResponse.GetMessage(),
		},
		Data: common.CardCVVInfo{
			CardID: req.CardID,
			CVV:    cvvResponse.Data.CVV,
		},
	}, nil
}

// HandleCardDetail 处理卡片详情查询
func (h *PhotonPayAdapterHandler) HandleCardDetail(ctx context.Context, req *common.CardDetailRequest) (*common.CardDetailResponse, error) {
	// 调用PhotonPay服务获取卡片详情
	result, err := photonpayServices.GetCardDetail(ctx, h.client, req.CardID)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡片详情失败", err.Error())
	}

	// 添加调试信息
	fmt.Printf("[DEBUG] PhotonPay GetCardDetail response: %s\n", string(result))

	// 首先尝试解析为通用响应格式
	var genericResponse map[string]interface{}
	if err := json.Unmarshal(result, &genericResponse); err != nil {
		fmt.Printf("[DEBUG] Failed to parse response: %v\n", err)
		return nil, NewPlatformError(h.platformID, "RESPONSE_PARSE_ERROR", "解析卡片详情响应失败", err.Error())
	}

	fmt.Printf("[DEBUG] Parsed response: %+v\n", genericResponse)

	// 检查响应状态
	code, ok := genericResponse["code"].(string)
	if !ok {
		return nil, NewPlatformError(h.platformID, "INVALID_RESPONSE", "响应格式无效", "无法获取响应状态码")
	}

	// 如果是错误响应
	if code != "0000" && code != "200" {
		// 直接返回错误信息，不尝试解析复杂的错误格式
		return nil, NewPlatformError(h.platformID, "API_ERROR", "获取卡片详情失败", "PhotonPay API 返回错误")
	}

	// 如果是成功响应，解析为详细格式
	// 定义详细的响应结构
	var detailResponse struct {
		Code string `json:"code"`
		Msg  string `json:"msg"`
		Data struct {
			CardID                    string      `json:"cardId"`
			CardNo                    string      `json:"cardNo"`
			MaskCardNo                string      `json:"maskCardNo"`
			CardBin                   string      `json:"cardBin"`
			CardScheme                string      `json:"cardScheme"`
			CardType                  string      `json:"cardType"`
			CardStatus                string      `json:"cardStatus"`
			CardBalance               interface{} `json:"cardBalance"`
			CardCurrency              string      `json:"cardCurrency"`
			CardFormFactor            string      `json:"cardFormFactor"`
			ExpirationDate            string      `json:"expirationDate"`
			CVV                       string      `json:"cvv"`
			FirstName                 string      `json:"firstName"`
			LastName                  string      `json:"lastName"`
			Email                     string      `json:"email"`
			Mobile                    string      `json:"mobile"`
			MobilePrefix              string      `json:"mobilePrefix"`
			BillingAddress            string      `json:"billingAddress"`
			BillingCity               string      `json:"billingCity"`
			BillingState              string      `json:"billingState"`
			BillingPostalCode         string      `json:"billingPostalCode"`
			BillingCountry            string      `json:"billingCountry"`
			Nationality               string      `json:"nationality"`
			Nickname                  string      `json:"nickname"`
			MatrixAccount             string      `json:"matrixAccount"`
			MemberID                  string      `json:"memberId"`
			CardholderID              string      `json:"cardholderId"`
			TransactionLimit          string      `json:"transactionLimit"`
			TransactionLimitType      string      `json:"transactionLimitType"`
			BillingAddressUpdatable   string      `json:"billingAddressUpdatable"`
			CreatedAt                 string      `json:"createdAt"`
			TotalTransferAmount       string      `json:"totalTransferAmount"`
			TotalTransactionLimit     interface{} `json:"totalTransactionLimit"`
			MaxOnDaily                interface{} `json:"maxOnDaily"`
			AvailableTransactionLimit interface{} `json:"availableTransactionLimit"`
		} `json:"data"`
	}

	// 重新解析为详细格式
	fmt.Printf("[DEBUG] 开始解析PhotonPay卡详情响应，原始数据长度: %d\n", len(result))
	fmt.Printf("[DEBUG] 原始响应数据: %s\n", string(result))

	if err := json.Unmarshal(result, &detailResponse); err != nil {
		fmt.Printf("[DEBUG] Failed to parse detail response: %v\n", err)
		fmt.Printf("[DEBUG] 尝试解析的JSON: %s\n", string(result))
		return nil, NewPlatformError(h.platformID, "RESPONSE_PARSE_ERROR", "解析卡片详情响应失败", err.Error())
	}

	fmt.Printf("[DEBUG] 成功解析响应，Code: %s, Msg: %s\n", detailResponse.Code, detailResponse.Msg)

	// 将PhotonPay的响应数据转换为统一格式
	cardDetail := detailResponse.Data

	// 解析余额
	var balance float64
	switch v := cardDetail.CardBalance.(type) {
	case float64:
		balance = v
	case int:
		balance = float64(v)
	case string:
		balance, _ = strconv.ParseFloat(v, 64)
	default:
		balance = 0
	}

	// 解析限额字段
	var totalTransactionLimit int
	var maxOnDaily int
	var availableTransactionLimit int

	// 解析总交易限额
	if cardDetail.TotalTransactionLimit != nil {
		switch v := cardDetail.TotalTransactionLimit.(type) {
		case float64:
			totalTransactionLimit = int(v)
		case int:
			totalTransactionLimit = v
		case string:
			if val, err := strconv.Atoi(v); err == nil {
				totalTransactionLimit = val
			}
		}
	}

	// 解析每日限额
	if cardDetail.MaxOnDaily != nil {
		switch v := cardDetail.MaxOnDaily.(type) {
		case float64:
			maxOnDaily = int(v)
		case int:
			maxOnDaily = v
		case string:
			if val, err := strconv.Atoi(v); err == nil {
				maxOnDaily = val
			}
		}
	}

	// 解析可用交易限额
	if cardDetail.AvailableTransactionLimit != nil {
		switch v := cardDetail.AvailableTransactionLimit.(type) {
		case float64:
			availableTransactionLimit = int(v)
		case int:
			availableTransactionLimit = v
		case string:
			if val, err := strconv.Atoi(v); err == nil {
				availableTransactionLimit = val
			}
		}
	}

	// 获取卡BIN（从卡号前6位）
	cardBin := ""
	if len(cardDetail.CardNo) >= 6 {
		cardBin = cardDetail.CardNo[:6]
	}

	// 获取卡Scheme（根据BIN判断）
	cardScheme := ""
	if strings.HasPrefix(cardBin, "4") {
		cardScheme = "VISA"
	} else if strings.HasPrefix(cardBin, "5") {
		cardScheme = "MASTERCARD"
	}

	// 转换卡状态格式
	cardStatus := "NORMAL"
	switch strings.ToUpper(cardDetail.CardStatus) {
	case "ACTIVE":
		cardStatus = "NORMAL"
	case "FROZEN":
		cardStatus = "FROZEN"
	case "CLOSED":
		cardStatus = "CLOSED"
	default:
		cardStatus = "NORMAL"
	}

	// 构建过期日期
	expirationDate := ""
	if cardDetail.ExpirationDate != "" {
		expirationDate = cardDetail.ExpirationDate
	}

	// 构建手机号
	mobile := cardDetail.Mobile
	mobilePrefix := ""
	if cardDetail.MobilePrefix != "" {
		mobilePrefix = cardDetail.MobilePrefix
	}

	// 构建账单地址
	billingAddress := cardDetail.BillingAddress
	if cardDetail.BillingCity != "" {
		if billingAddress != "" {
			billingAddress += ", "
		}
		billingAddress += cardDetail.BillingCity
	}
	if cardDetail.BillingState != "" {
		if billingAddress != "" {
			billingAddress += ", "
		}
		billingAddress += cardDetail.BillingState
	}

	response := &common.CardDetailResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000", // 转换为统一成功码
			Msg:  "success",
		},
		Data: common.CardDetailInfo{
			CardID:                    cardDetail.CardID,
			CardNo:                    cardDetail.CardNo,
			MaskCardNo:                cardDetail.MaskCardNo,
			CardBin:                   cardBin,
			CardScheme:                cardScheme,
			CardType:                  cardDetail.CardType,
			CardStatus:                cardStatus,
			CardBalance:               balance,
			CardCurrency:              cardDetail.CardCurrency,
			CardFormFactor:            cardDetail.CardFormFactor,
			ExpirationDate:            expirationDate,
			CVV:                       cardDetail.CVV,
			FirstName:                 cardDetail.FirstName,
			LastName:                  cardDetail.LastName,
			Email:                     cardDetail.Email,
			Mobile:                    mobile,
			MobilePrefix:              mobilePrefix,
			BillingAddress:            billingAddress,
			BillingCity:               cardDetail.BillingCity,
			BillingState:              cardDetail.BillingState,
			BillingPostalCode:         cardDetail.BillingPostalCode,
			BillingCountry:            cardDetail.BillingCountry,
			Nationality:               cardDetail.Nationality,
			Nickname:                  cardDetail.Nickname,
			MatrixAccount:             cardDetail.MatrixAccount,
			MemberID:                  cardDetail.MemberID,
			CardholderID:              cardDetail.CardholderID,
			TransactionLimit:          nil, // PhotonPay没有交易限额字段
			TransactionLimitType:      cardDetail.TransactionLimitType,
			TotalTransactionLimit:     totalTransactionLimit,
			MaxOnDaily:                maxOnDaily,
			AvailableTransactionLimit: availableTransactionLimit,
			BillingAddressUpdatable:   cardDetail.BillingAddressUpdatable,
			CreatedAt:                 cardDetail.CreatedAt,
			TotalTransferAmount:       0, // PhotonPay没有总转账金额字段
		},
	}

	// 打印调试信息
	fmt.Printf("[PhotonPayAdapterHandler] 卡片 %s 限额信息: TotalTransactionLimit=%d, MaxOnDaily=%d, AvailableTransactionLimit=%d\n",
		cardDetail.CardID, totalTransactionLimit, maxOnDaily, availableTransactionLimit)

	return response, nil
}

// HandleCardholderList 处理持卡人列表查询
func (h *PhotonPayAdapterHandler) HandleCardholderList(ctx context.Context, req *common.CardholderListRequest) (*common.CardholderListResponse, error) {
	// 从上下文中获取matrixAccount信息（如果请求中没有提供）
	matrixAccount := req.MatrixAccount
	if matrixAccount == "" {
		if matrixInfo := ctx.Value("matrix_account_info"); matrixInfo != nil {
			if matrixAccountInfo, ok := matrixInfo.(*models.UserMatrixAccount); ok {
				matrixAccount = matrixAccountInfo.MatrixAccount
			}
		}
	}

	if matrixAccount == "" {
		return nil, NewPlatformError(h.platformID, "MISSING_PARAMETER", "缺少matrixAccount参数", "查询持卡人列表需要matrixAccount")
	}

	fmt.Printf("[PhotonPayAdapterHandler] 使用matrixAccount查询持卡人列表: %s\n", matrixAccount)

	// 构建PhotonPay查询参数 - 获取较大的数据量以支持本地过滤和分页
	params := photonpayModels.CardholderQueryParams{
		PageIndex:     1,   // 固定获取第一页
		PageSize:      100, // 获取较大的数据量
		MatrixAccount: matrixAccount,
	}

	// 从上下文中获取额外的查询参数
	if ctx.Value("cardholder_id") != nil {
		if cardholderID, ok := ctx.Value("cardholder_id").(string); ok && cardholderID != "" {
			params.CardholderID = cardholderID
		}
	}

	if ctx.Value("status") != nil {
		if status, ok := ctx.Value("status").(string); ok && status != "" {
			params.Status = status
		}
	}

	if ctx.Value("name") != nil {
		if name, ok := ctx.Value("name").(string); ok && name != "" {
			params.Name = name
		}
	}
	if ctx.Value("first_name") != nil {
		if firstName, ok := ctx.Value("first_name").(string); ok && firstName != "" {
			params.FirstName = firstName
		}
	}
	if ctx.Value("last_name") != nil {
		if lastName, ok := ctx.Value("last_name").(string); ok && lastName != "" {
			params.LastName = lastName
		}
	}

	if ctx.Value("created_at_start") != nil {
		if createdAtStart, ok := ctx.Value("created_at_start").(string); ok && createdAtStart != "" {
			params.CreatedAtStart = createdAtStart
		}
	}

	if ctx.Value("created_at_end") != nil {
		if createdAtEnd, ok := ctx.Value("created_at_end").(string); ok && createdAtEnd != "" {
			params.CreatedAtEnd = createdAtEnd
		}
	}

	// 调用PhotonPay服务
	result, err := photonpayServices.GetCardholderList(ctx, h.client, params)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取持卡人列表失败", err.Error())
	}

	// 转换为统一格式
	response := &common.CardholderListResponse{
		BaseResponse: common.BaseResponse{
			Code: result.Code,
			Msg:  result.Msg,
		},
		PageIndex: req.PageIndex, // 使用请求的分页参数
		PageSize:  req.PageSize,  // 使用请求的分页参数
		Total:     0,             // 稍后计算
	}

	// 转换持卡人信息并进行本地过滤
	if result.Data != nil {
		var filteredData []common.CardholderInfo

		// 从上下文中获取name参数进行本地过滤
		var nameFilter string
		if ctx.Value("name") != nil {
			if name, ok := ctx.Value("name").(string); ok && name != "" {
				nameFilter = strings.ToUpper(name)
			}
		}

		for _, cardholder := range result.Data {
			// 如果有name过滤条件，进行本地过滤
			if nameFilter != "" {
				// 改进的姓名匹配逻辑，支持 XU/YU 格式
				firstName := strings.ToUpper(cardholder.FirstName)
				lastName := strings.ToUpper(cardholder.LastName)

				// 检查是否包含 / 分割符
				if strings.Contains(nameFilter, "/") {
					// 使用 / 分割姓名
					parts := strings.Split(nameFilter, "/")
					if len(parts) == 2 {
						searchFirstName := strings.TrimSpace(parts[0])
						searchLastName := strings.TrimSpace(parts[1])

						// 检查firstName和lastName是否匹配
						firstNameMatch := strings.Contains(firstName, searchFirstName) || strings.Contains(searchFirstName, firstName)
						lastNameMatch := strings.Contains(lastName, searchLastName) || strings.Contains(searchLastName, lastName)

						// 同时匹配firstName和lastName
						if firstNameMatch && lastNameMatch {
							// 匹配成功，继续处理这条记录
						} else {
							// 尝试反向匹配（交换firstName和lastName）
							firstNameMatchReverse := strings.Contains(firstName, searchLastName) || strings.Contains(searchLastName, firstName)
							lastNameMatchReverse := strings.Contains(lastName, searchFirstName) || strings.Contains(searchFirstName, lastName)

							if !(firstNameMatchReverse && lastNameMatchReverse) {
								continue // 跳过不匹配的记录
							}
						}
					} else {
						// 分割后不是2个部分，使用原来的模糊匹配逻辑
						directMatch := strings.Contains(firstName, nameFilter) || strings.Contains(lastName, nameFilter)
						if !directMatch {
							continue
						}
					}
				} else {
					// 没有 / 分割符，使用原来的模糊匹配逻辑
					// 1. 检查firstName或lastName是否直接包含搜索词
					directMatch := strings.Contains(firstName, nameFilter) || strings.Contains(lastName, nameFilter)

					// 2. 检查firstName + lastName的组合是否包含搜索词
					fullName := firstName + lastName
					combinedMatch := strings.Contains(fullName, nameFilter)

					// 3. 检查lastName + firstName的组合是否包含搜索词
					reverseFullName := lastName + firstName
					reverseCombinedMatch := strings.Contains(reverseFullName, nameFilter)

					// 如果所有匹配方式都失败，跳过这条记录
					if !directMatch && !combinedMatch && !reverseCombinedMatch {
						continue
					}
				}
			}

			// 转换持卡人信息
			cardholderInfo := common.CardholderInfo{
				CardholderID:           cardholder.CardholderID,
				FirstName:              cardholder.FirstName,
				LastName:               cardholder.LastName,
				Email:                  cardholder.Email,
				Mobile:                 cardholder.Mobile,
				MobilePrefix:           cardholder.MobilePrefix,
				DateOfBirth:            cardholder.DateOfBirth,
				NationalityCountryCode: cardholder.NationalityCountryCode,
				Status:                 cardholder.Status,
				CreatedAt:              cardholder.CreatedAt,
				MatrixAccount:          cardholder.MatrixAccount,
				MemberID:               cardholder.MemberID,
				ResidentialAddress:     cardholder.ResidentialAddress,
				ResidentialCity:        cardholder.ResidentialCity,
				ResidentialState:       cardholder.ResidentialState,
				ResidentialPostalCode:  cardholder.ResidentialPostalCode,
				ResidentialCountryCode: cardholder.ResidentialCountryCode,
			}

			filteredData = append(filteredData, cardholderInfo)
		}

		// 计算分页
		total := int64(len(filteredData))
		response.Total = total

		// 计算分页范围
		start := int((req.PageIndex - 1) * req.PageSize)
		end := start + int(req.PageSize)

		// 应用分页
		if start >= len(filteredData) {
			// 起始位置超出范围，返回空数据
			response.Data = []common.CardholderInfo{}
		} else if end > len(filteredData) {
			// 结束位置超出范围，返回从start到末尾的数据
			response.Data = filteredData[start:]
		} else {
			// 正常分页
			response.Data = filteredData[start:end]
		}

		fmt.Printf("[PhotonPayAdapterHandler] 成功获取持卡人列表，过滤前 %d 条记录，过滤后 %d 条记录，分页后 %d 条记录\n",
			len(result.Data), total, len(response.Data))

		// 添加调试信息
		if nameFilter != "" {
			fmt.Printf("[PhotonPayAdapterHandler] 使用姓名过滤条件: %s\n", nameFilter)
			if strings.Contains(nameFilter, "/") {
				parts := strings.Split(nameFilter, "/")
				if len(parts) == 2 {
					fmt.Printf("[PhotonPayAdapterHandler] 解析姓名: firstName=%s, lastName=%s\n",
						strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]))
				}
			}
		}
	}

	return response, nil
}

// HandleCreateCardholder 处理创建持卡人请求
func (h *PhotonPayAdapterHandler) HandleCreateCardholder(ctx context.Context, req *common.CreateCardholderRequest) (*common.CreateCardholderResponse, error) {
	// 从上下文中获取matrixAccount信息
	var matrixAccount string

	// 尝试从不同的上下文键中获取matrixAccount
	fmt.Printf("[PhotonPayAdapterHandler] 开始获取matrixAccount信息...\n")

	// 方法1: 尝试从matrix_account_info获取
	if matrixInfo := ctx.Value("matrix_account_info"); matrixInfo != nil {
		fmt.Printf("[PhotonPayAdapterHandler] 找到matrix_account_info: %+v\n", matrixInfo)
		if matrixAccountInfo, ok := matrixInfo.(*models.UserMatrixAccount); ok {
			matrixAccount = matrixAccountInfo.MatrixAccount
			fmt.Printf("[PhotonPayAdapterHandler] 从matrix_account_info获取到matrixAccount: %s\n", matrixAccount)
		}
	}

	// 方法2: 尝试从platform_info获取
	if matrixAccount == "" {
		if platformInfo := ctx.Value("platform_info"); platformInfo != nil {
			fmt.Printf("[PhotonPayAdapterHandler] 找到platform_info: %+v\n", platformInfo)
			if platform, ok := platformInfo.(*middleware.PlatformInfo); ok {
				matrixAccount = platform.MatrixAccount
				fmt.Printf("[PhotonPayAdapterHandler] 从platform_info获取到matrixAccount: %s\n", matrixAccount)
			}
		}
	}

	// 方法3: 尝试从claims获取用户ID，然后查询数据库
	if matrixAccount == "" {
		if claims := ctx.Value("claims"); claims != nil {
			fmt.Printf("[PhotonPayAdapterHandler] 找到claims: %+v\n", claims)
			if authClaims, ok := claims.(*auth.Claims); ok {
				fmt.Printf("[PhotonPayAdapterHandler] 从claims获取到用户ID: %d\n", authClaims.UserID)
				// 从数据库查询matrixAccount
				var userMatrixAccount models.UserMatrixAccount
				if err := database.DB.Where("user_id = ? AND status = 'active'", authClaims.UserID).First(&userMatrixAccount).Error; err == nil {
					matrixAccount = userMatrixAccount.MatrixAccount
					fmt.Printf("[PhotonPayAdapterHandler] 从数据库查询到matrixAccount: %s\n", matrixAccount)
				} else {
					fmt.Printf("[PhotonPayAdapterHandler] 从数据库查询matrixAccount失败: %v\n", err)
				}
			}
		}
	}

	if matrixAccount == "" {
		fmt.Printf("[PhotonPayAdapterHandler] 无法获取matrixAccount，所有方法都失败了\n")
		return nil, NewPlatformError(h.platformID, "MISSING_PARAMETER", "缺少matrixAccount参数", "创建持卡人需要matrixAccount")
	}

	fmt.Printf("[PhotonPayAdapterHandler] 最终使用matrixAccount创建持卡人: %s\n", matrixAccount)

	// 构建PhotonPay创建持卡人请求
	createCardholderRequest := map[string]interface{}{
		"matrixAccount":              matrixAccount,
		"firstName":                  req.FirstName,
		"lastName":                   req.LastName,
		"cardholderNameAbbreviation": req.CardholderNameAbbreviation,
		"email":                      req.Email,
		"mobile":                     req.Mobile,
		"mobilePrefix":               req.MobilePrefix,
		"dateOfBirth":                req.DateOfBirth,
		"certType":                   req.CertType,
		"portrait":                   req.Portrait,
		"reverseSide":                req.ReverseSide,
		"nationalityCountryCode":     req.NationalityCountryCode,
		"residentialAddress":         req.ResidentialAddress,
		"residentialCity":            req.ResidentialCity,
		"residentialCountryCode":     req.ResidentialCountryCode,
		"residentialPostalCode":      req.ResidentialPostalCode,
		"residentialState":           req.ResidentialState,
	}

	// 序列化请求体
	bodyBytes, err := json.Marshal(createCardholderRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "JSON_ERROR", "序列化请求失败", err.Error())
	}

	fmt.Printf("[PhotonPayAdapterHandler] 创建持卡人请求体: %s\n", string(bodyBytes))

	// 调用PhotonPay创建持卡人服务
	result, err := photonpayServices.AddCardholder(ctx, h.client, bodyBytes)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "创建持卡人失败", err.Error())
	}

	// 打印原始响应用于调试
	fmt.Printf("[PhotonPayAdapterHandler] 创建持卡人原始响应: %s\n", string(result))

	// 解析响应为通用格式
	var response map[string]interface{}
	if err := json.Unmarshal(result, &response); err != nil {
		fmt.Printf("[PhotonPayAdapterHandler] JSON解析失败: %v\n", err)
		fmt.Printf("[PhotonPayAdapterHandler] 尝试解析的数据: %s\n", string(result))
		return nil, NewPlatformError(h.platformID, "PARSE_ERROR", "解析创建持卡人响应失败", err.Error())
	}

	// 检查响应状态
	if code, ok := response["code"].(string); !ok || (code != "0000" && code != "200") {
		// 处理msg字段，可能是字符串或对象
		var msgStr string
		if msgObj, ok := response["msg"].(map[string]interface{}); ok {
			// msg是对象，提取CN字段
			if cn, ok := msgObj["CN"].(string); ok {
				msgStr = cn
			} else {
				msgStr = "创建持卡人失败"
			}
		} else if msg, ok := response["msg"].(string); ok {
			// msg是字符串
			msgStr = msg
		} else {
			msgStr = "创建持卡人失败"
		}

		return nil, NewPlatformError(h.platformID, "API_ERROR", msgStr, "创建持卡人失败")
	}

	// 提取持卡人ID
	var cardholderID string
	if data, ok := response["data"]; ok {
		if dataStr, ok := data.(string); ok {
			cardholderID = dataStr
		} else if dataMap, ok := data.(map[string]interface{}); ok {
			if id, ok := dataMap["cardholderId"].(string); ok {
				cardholderID = id
			}
		}
	}

	if cardholderID == "" {
		return nil, NewPlatformError(h.platformID, "API_ERROR", "响应中缺少持卡人ID", "创建持卡人失败")
	}

	// 返回统一格式的响应
	createCardholderResponse := &common.CreateCardholderResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: cardholderID, // 返回持卡人ID
	}

	fmt.Printf("[PhotonPayAdapterHandler] 成功创建持卡人: %s, MatrixAccount: %s\n", cardholderID, matrixAccount)

	return createCardholderResponse, nil
}

// HandleUpdateCardholder 处理更新持卡人请求
func (h *PhotonPayAdapterHandler) HandleUpdateCardholder(ctx context.Context, req *common.UpdateCardholderRequest) (*common.UpdateCardholderResponse, error) {
	// 构建PhotonPay更新持卡人请求，所有字段都传递
	updateCardholderRequest := map[string]interface{}{
		"cardholderId":               req.CardholderID,
		"firstName":                  req.FirstName,
		"lastName":                   req.LastName,
		"cardholderNameAbbreviation": req.CardholderNameAbbreviation,
		"email":                      req.Email,
		"mobile":                     req.Mobile,
		"status":                     req.Status,
		"dateOfBirth":                getStringOrDefault(req.DateOfBirth, "2000-01-01"),
		"nationalityCountryCode":     getStringOrDefault(req.NationalityCountryCode, "HK"),
		"mobilePrefix":               getStringOrDefault(req.MobilePrefix, "86"),
		"certType":                   getStringOrDefault(req.CertType, "id_card"),
		"portrait":                   getStringOrDefault(req.Portrait, ""),
		"reverseSide":                getStringOrDefault(req.ReverseSide, ""),
		"residentialAddress":         getStringOrDefault(req.ResidentialAddress, ""),
		"residentialCity":            getStringOrDefault(req.ResidentialCity, ""),
		"residentialCountryCode":     getStringOrDefault(req.ResidentialCountryCode, "HK"),
		"residentialPostalCode":      getStringOrDefault(req.ResidentialPostalCode, ""),
		"residentialState":           getStringOrDefault(req.ResidentialState, ""),
	}

	// 序列化请求体
	bodyBytes, err := json.Marshal(updateCardholderRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "JSON_ERROR", "序列化请求失败", err.Error())
	}

	// 调用PhotonPay更新持卡人服务
	result, err := photonpayServices.EditCardholder(ctx, h.client, bodyBytes)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "更新持卡人失败", err.Error())
	}

	// 打印原始响应用于调试
	fmt.Printf("[PhotonPayAdapterHandler] 更新持卡人原始响应: %s\n", string(result))

	// 解析响应为通用格式
	var response map[string]interface{}
	if err := json.Unmarshal(result, &response); err != nil {
		fmt.Printf("[PhotonPayAdapterHandler] JSON解析失败: %v\n", err)
		fmt.Printf("[PhotonPayAdapterHandler] 尝试解析的数据: %s\n", string(result))
		return nil, NewPlatformError(h.platformID, "PARSE_ERROR", "解析更新持卡人响应失败", err.Error())
	}

	// 检查响应状态
	if code, ok := response["code"].(string); !ok || (code != "0000" && code != "200") {
		// 处理msg字段，可能是字符串或对象
		var msgStr string
		if msgObj, ok := response["msg"].(map[string]interface{}); ok {
			// msg是对象，提取CN字段
			if cn, ok := msgObj["CN"].(string); ok {
				msgStr = cn
			} else {
				msgStr = "更新持卡人失败"
			}
		} else if msg, ok := response["msg"].(string); ok {
			// msg是字符串
			msgStr = msg
		} else {
			msgStr = "更新持卡人失败"
		}

		return nil, NewPlatformError(h.platformID, "API_ERROR", msgStr, "更新持卡人失败")
	}

	// 返回统一格式的响应，所有字段都返回
	updateCardholderResponse := &common.UpdateCardholderResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: common.CardholderInfo{
			CardholderID:               req.CardholderID,
			FirstName:                  req.FirstName,
			LastName:                   req.LastName,
			CardholderNameAbbreviation: req.CardholderNameAbbreviation,
			Email:                      req.Email,
			Mobile:                     req.Mobile,
			MobilePrefix:               req.MobilePrefix,
			DateOfBirth:                req.DateOfBirth,
			CertType:                   req.CertType,
			Portrait:                   req.Portrait,
			ReverseSide:                req.ReverseSide,
			NationalityCountryCode:     req.NationalityCountryCode,
			ResidentialAddress:         req.ResidentialAddress,
			ResidentialCity:            req.ResidentialCity,
			ResidentialCountryCode:     req.ResidentialCountryCode,
			ResidentialPostalCode:      req.ResidentialPostalCode,
			ResidentialState:           req.ResidentialState,
			Status:                     req.Status,
			CreatedAt:                  "",
			MatrixAccount:              "",
			MemberID:                   "",
			IsLegal:                    "",
			CardholderReviewStatus:     "",
			Reason:                     "",
		},
	}

	return updateCardholderResponse, nil
}

// HandleCardHistoryList 处理卡片历史列表查询
func (h *PhotonPayAdapterHandler) HandleCardHistoryList(ctx context.Context, req *common.CardHistoryListRequest) (*common.CardHistoryListResponse, error) {
	// 构建PhotonPay查询参数
	params := photonpayModels.IssuingHistoryQueryParams{
		PageIndex:      int64(req.PageIndex),
		PageSize:       int64(req.PageSize),
		CardID:         req.CardID,
		CardFormFactor: req.CardFormFactor,
		Status:         req.Status,
		FeeType:        req.FeeType,
		CreatedAtStart: req.CreatedAtStart,
		CreatedAtEnd:   req.CreatedAtEnd,
	}

	// 调用PhotonPay服务
	result, err := photonpayServices.GetIssuingHistoryList(ctx, h.client, params)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取卡片历史失败", err.Error())
	}

	// 转换为统一格式
	response := &common.CardHistoryListResponse{
		BaseResponse: common.BaseResponse{
			Code: result.Code,
			Msg:  string(result.Msg),
		},
		PageIndex: req.PageIndex,
		PageSize:  req.PageSize,
		Total:     result.Total,
	}

	// 转换历史信息
	if result.Data != nil {
		response.Data = make([]common.CardHistoryInfo, len(result.Data))
		for i, history := range result.Data {
			response.Data[i] = common.CardHistoryInfo{
				ActualFeeAmount:   history.ActualFeeAmount,
				ActualFeeCurrency: history.ActualFeeCurrency,
				CardID:            history.CardID,
				CardScheme:        history.CardScheme,
				CardType:          history.CardType,
				CreatedAt:         history.CreatedAt,
				FeeType:           history.FeeType,
				MaskCardNo:        history.MaskCardNo,
				MemberID:          history.MemberID,
				MatrixAccount:     history.MatrixAccount,
				Nickname:          history.Nickname,
				ReferenceNo:       history.ReferenceNo,
				Status:            history.Status,
				CardFormFactor:    history.CardFormFactor,
				CardNickname:      history.CardNickname,
			}
		}
	}

	return response, nil
}

// HandleOpenCard 处理开卡请求
func (h *PhotonPayAdapterHandler) HandleOpenCard(ctx context.Context, req *common.OpenCardRequest) (*common.OpenCardResponse, error) {
	// 构建PhotonPay开卡请求
	openCardRequest := map[string]interface{}{
		"userId":               req.UserID,
		"matrixAccount":        req.MatrixAccount,
		"accountId":            req.AccountID,
		"cardBin":              req.CardBin,
		"cardholderId":         req.CardholderID,
		"cardCurrency":         req.CardCurrency,
		"cardExpirationDate":   req.CardExpirationDate,
		"cardScheme":           req.CardScheme,
		"cardType":             req.CardType,
		"cardFormFactor":       req.CardFormFactor,
		"rechargeAmount":       req.RechargeAmount,
		"requestId":            req.RequestID,
		"transactionLimitType": req.TransactionLimitType,
	}

	// 序列化请求体
	bodyBytes, err := json.Marshal(openCardRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "JSON_ERROR", "序列化请求失败", err.Error())
	}

	// 调用PhotonPay开卡服务
	result, err := photonpayServices.OpenCard(ctx, h.client, bodyBytes)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "开卡失败", err.Error())
	}

	// 打印原始响应用于调试
	fmt.Printf("平台处理器原始响应: %s\n", string(result))
	fmt.Printf("平台处理器响应字节: %v\n", result)

	// 解析响应为通用格式
	var response map[string]interface{}
	if err := json.Unmarshal(result, &response); err != nil {
		fmt.Printf("平台处理器JSON解析失败: %v\n", err)
		fmt.Printf("平台处理器尝试解析的数据: %s\n", string(result))
		return nil, NewPlatformError(h.platformID, "PARSE_ERROR", "解析开卡响应失败", err.Error())
	}

	// 检查响应状态
	if code, ok := response["code"].(string); !ok || (code != "0000" && code != "200") {
		// 处理msg字段，可能是字符串或对象
		var msgStr string
		if msgObj, ok := response["msg"].(map[string]interface{}); ok {
			// msg是对象，提取CN字段
			if cn, ok := msgObj["CN"].(string); ok {
				msgStr = cn
			} else {
				msgStr = "开卡失败"
			}
		} else if msg, ok := response["msg"].(string); ok {
			// msg是字符串
			msgStr = msg
		} else {
			msgStr = "开卡失败"
		}

		return nil, NewPlatformError(h.platformID, "API_ERROR", msgStr, "开卡失败")
	}

	// 检查是否有data字段
	data, ok := response["data"]
	if !ok {
		return nil, NewPlatformError(h.platformID, "API_ERROR", "响应中缺少data字段", "开卡失败")
	}

	// 提取卡片ID
	var cardID string
	if dataMap, ok := data.(map[string]interface{}); ok {
		if cardId, ok := dataMap["cardId"].(string); ok {
			cardID = cardId
		} else {
			return nil, NewPlatformError(h.platformID, "API_ERROR", "响应中缺少cardId字段", "开卡失败")
		}
	} else {
		return nil, NewPlatformError(h.platformID, "API_ERROR", "data字段格式错误", "开卡失败")
	}

	// 返回统一格式的响应
	openCardResponse := &common.OpenCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: cardID, // 返回卡片ID
	}

	return openCardResponse, nil
}

// HandleBatchOpenCard 处理批量开卡请求
func (h *PhotonPayAdapterHandler) HandleBatchOpenCard(ctx context.Context, req *common.BatchOpenCardRequest) (*common.BatchOpenCardResponse, error) {
	// 设置默认开卡数量为1
	cardCount := req.CardCount
	if cardCount <= 0 {
		cardCount = 1
	}

	// 设置默认超时时间为15秒
	timeoutSeconds := req.TimeoutSeconds
	if timeoutSeconds <= 0 {
		timeoutSeconds = 15
	}

	// 批量开卡结果
	var batchResults []common.CardResult
	var successCount int
	var failedCount int

	// 批量开卡 - 使用独立事务处理每张卡
	for i := 1; i <= cardCount; i++ {
		// 生成卡昵称：用户输入名称+[序号]
		cardNikeName := req.Nickname
		if cardCount > 1 {
			cardNikeName = fmt.Sprintf("%s[%d]", req.Nickname, i)
		}

		// 生成唯一的requestId
		uniqueRequestId := fmt.Sprintf("%s_%d", req.RequestID, i)

		// 记录调试信息
		fmt.Printf("Processing card %d/%d: nikeName=%s, requestId=%s", i, cardCount, cardNikeName, uniqueRequestId)

		// 构建PhotonPay开卡请求
		openCardRequest := map[string]interface{}{
			"userId":               req.UserID,
			"matrixAccount":        req.MatrixAccount,
			"accountId":            req.AccountID,
			"cardBin":              req.CardBin,
			"cardholderId":         req.CardholderID,
			"cardCurrency":         req.CardCurrency,
			"cardExpirationDate":   req.CardExpirationDate,
			"cardScheme":           req.CardScheme,
			"cardType":             req.CardType,
			"cardFormFactor":       req.CardFormFactor,
			"rechargeAmount":       req.RechargeAmount,
			"requestId":            uniqueRequestId,
			"transactionLimitType": req.TransactionLimitType,
			"nikeName":             cardNikeName,
		}

		// 序列化请求体
		bodyBytes, err := json.Marshal(openCardRequest)
		if err != nil {
			failedCount++
			batchResults = append(batchResults, common.CardResult{
				CardIndex: i,
				Status:    "failed",
				Error:     "request_marshal_failed",
				Details:   err.Error(),
			})
			continue
		}

		// 创建带超时的上下文
		ctxWithTimeout, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second)
		defer cancel()

		// 添加重试机制
		var result []byte
		var apiErr error
		maxRetries := 2
		for retry := 0; retry <= maxRetries; retry++ {
			if retry > 0 {
				fmt.Printf("Retrying card %d, attempt %d/%d", i, retry+1, maxRetries+1)
				// 重试前等待一小段时间
				time.Sleep(time.Duration(retry) * 500 * time.Millisecond)
			}

			result, apiErr = photonpayServices.OpenCard(ctxWithTimeout, h.client, bodyBytes)
			if apiErr == nil {
				break
			}

			// 检查是否是超时错误，如果是则重试
			if ctxWithTimeout.Err() == context.DeadlineExceeded {
				fmt.Printf("Card %d request timeout on attempt %d (%ds)", i, retry+1, timeoutSeconds)
				if retry == maxRetries {
					failedCount++
					batchResults = append(batchResults, common.CardResult{
						CardIndex: i,
						Status:    "failed",
						Error:     "request_timeout",
						Details:   fmt.Sprintf("timeout: %ds, retries: %d", timeoutSeconds, retry+1),
					})
					break
				}
				continue
			}

			// 其他错误，记录但不重试
			fmt.Printf("Failed to open card %d on attempt %d: %v", i, retry+1, apiErr)
			if retry == maxRetries {
				failedCount++
				batchResults = append(batchResults, common.CardResult{
					CardIndex: i,
					Status:    "failed",
					Error:     apiErr.Error(),
					Details:   fmt.Sprintf("retries: %d", retry+1),
				})
			}
			break
		}

		if apiErr != nil {
			continue
		}

		// 解析响应数据
		var responseData map[string]interface{}
		if err := json.Unmarshal(result, &responseData); err != nil {
			failedCount++
			batchResults = append(batchResults, common.CardResult{
				CardIndex: i,
				Status:    "failed",
				Error:     "parse_response_failed",
				Details:   err.Error(),
			})
			continue
		}

		// 检查开卡是否成功
		if code, ok := responseData["code"].(string); ok && (code == "0000" || code == "200") {
			if data, ok := responseData["data"].(map[string]interface{}); ok {
				if cardID, ok := data["cardId"].(string); ok {
					successCount++
					batchResults = append(batchResults, common.CardResult{
						CardIndex: i,
						Status:    "success",
						CardID:    cardID,
						NikeName:  cardNikeName,
						Data:      responseData,
					})
				} else {
					failedCount++
					batchResults = append(batchResults, common.CardResult{
						CardIndex: i,
						Status:    "failed",
						Error:     "card_id_not_found",
						Data:      responseData,
					})
				}
			} else {
				failedCount++
				batchResults = append(batchResults, common.CardResult{
					CardIndex: i,
					Status:    "failed",
					Error:     "response_data_not_found",
					Data:      responseData,
				})
			}
		} else {
			failedCount++
			// 获取错误信息，处理可能为null的情况
			var errorMsg interface{}
			if msg, exists := responseData["message"]; exists && msg != nil {
				errorMsg = msg
			} else if msg, exists := responseData["msg"]; exists && msg != nil {
				errorMsg = msg
			} else {
				errorMsg = "unknown_error"
			}

			batchResults = append(batchResults, common.CardResult{
				CardIndex: i,
				Status:    "failed",
				Error:     fmt.Sprintf("%v", errorMsg),
				Data:      responseData,
			})
		}
	}

	// 构建批量开卡结果
	batchResult := &common.BatchOpenCardResult{
		BatchSummary: common.BatchSummary{
			TotalCards:   cardCount,
			SuccessCount: successCount,
			FailedCount:  failedCount,
			SuccessRate:  fmt.Sprintf("%.2f%%", float64(successCount)/float64(cardCount)*100),
		},
		CardResults: batchResults,
		Message:     fmt.Sprintf("批量开卡完成：成功 %d 张，失败 %d 张", successCount, failedCount),
	}

	// 返回统一格式的响应
	response := &common.BatchOpenCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: batchResult,
	}

	return response, nil
}

// HandleRechargeCard 处理卡片充值请求
func (h *PhotonPayAdapterHandler) HandleRechargeCard(ctx context.Context, req *common.RechargeCardRequest) (*common.RechargeCardResponse, error) {
	// 构建PhotonPay充值请求
	rechargeRequest := map[string]interface{}{
		"cardId":    req.CardID,
		"amount":    req.Amount,
		"remark":    req.Remark,
		"requestId": req.RequestID,
	}

	// 添加调试日志
	fmt.Printf("[PhotonPayAdapterHandler] 充值请求体: %+v\n", rechargeRequest)

	// 序列化请求体
	bodyBytes, err := json.Marshal(rechargeRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "JSON_ERROR", "序列化请求失败", err.Error())
	}

	// 调用PhotonPay充值服务
	result, err := photonpayServices.Recharge(ctx, h.client, bodyBytes)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "充值失败", err.Error())
	}

	// 添加调试日志，打印PhotonPay服务返回的原始响应
	fmt.Printf("[PhotonPayAdapterHandler] PhotonPay服务返回的原始响应: %s\n", string(result))

	// 解析PhotonPay响应
	var response map[string]interface{}
	if err := json.Unmarshal(result, &response); err != nil {
		return nil, NewPlatformError(h.platformID, "PARSE_ERROR", "解析充值响应失败", err.Error())
	}

	// 添加调试日志，打印解析后的响应
	fmt.Printf("[PhotonPayAdapterHandler] 解析后的响应: %+v\n", response)

	// 检查响应状态
	if code, ok := response["code"].(string); !ok || (code != "0000" && code != "200") {
		// 处理msg字段，可能是字符串或对象
		var msgStr string
		if msgObj, ok := response["msg"].(map[string]interface{}); ok {
			// msg是对象，提取CN字段
			if cn, ok := msgObj["CN"].(string); ok {
				msgStr = cn
			} else {
				msgStr = "充值失败"
			}
		} else if msg, ok := response["msg"].(string); ok {
			// msg是字符串
			msgStr = msg
		} else {
			msgStr = "充值失败"
		}
		return nil, NewPlatformError(h.platformID, "API_ERROR", msgStr, "充值失败")
	}

	// 添加调试日志
	fmt.Printf("[PhotonPayAdapterHandler] 充值成功，响应码: %s\n", response["code"])

	// 返回统一格式的响应
	rechargeResponse := &common.RechargeCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: response["data"],
	}

	return rechargeResponse, nil
}

// HandleWithdrawCard 处理卡片提现请求
func (h *PhotonPayAdapterHandler) HandleWithdrawCard(ctx context.Context, req *common.WithdrawCardRequest) (*common.WithdrawCardResponse, error) {
	// PhotonPay的提现逻辑
	fmt.Printf("[PhotonPay] 开始处理提现请求 - CardID: %s, Amount: %f, Remark: %s\n",
		req.CardID, req.Amount, req.Remark)

	// 这里需要根据PhotonPay的实际API实现提现逻辑
	// 目前返回成功响应，实际使用时需要调用PhotonPay的提现API

	// TODO: 实现PhotonPay的提现API调用
	// 示例代码：
	// requestBody := map[string]interface{}{
	//     "cardId": req.CardID,
	//     "amount": req.Amount,
	//     "remark": req.Remark,
	// }
	// result, err := photonpayServices.WithdrawCard(ctx, h.client, requestBody)
	// if err != nil {
	//     return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "提现失败", err.Error())
	// }

	fmt.Printf("[PhotonPay] 提现请求处理完成 - CardID: %s\n", req.CardID)

	response := &common.WithdrawCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: map[string]interface{}{
			"cardId": req.CardID,
			"amount": req.Amount,
			"note":   "PhotonPay提现功能待实现",
		},
	}

	return response, nil
}

// HandleFreezeCard 处理卡片冻结请求
func (h *PhotonPayAdapterHandler) HandleFreezeCard(ctx context.Context, req *common.FreezeCardRequest) (*common.FreezeCardResponse, error) {
	// 构建PhotonPay冻结请求
	freezeRequest := map[string]interface{}{
		"cardId": req.CardID,
	}

	// 序列化请求体
	bodyBytes, err := json.Marshal(freezeRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "JSON_ERROR", "序列化请求失败", err.Error())
	}

	// 调用PhotonPay冻结服务
	result, err := photonpayServices.FreezeCard(ctx, h.client, bodyBytes)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "冻结卡片失败", err.Error())
	}

	// 解析PhotonPay响应
	var response map[string]interface{}
	if err := json.Unmarshal(result, &response); err != nil {
		return nil, NewPlatformError(h.platformID, "PARSE_ERROR", "解析冻结响应失败", err.Error())
	}

	// 检查响应状态
	if code, ok := response["code"].(string); !ok || code != "0000" {
		// 处理msg字段，可能是字符串或对象
		var msgStr string
		if msgObj, ok := response["msg"].(map[string]interface{}); ok {
			// msg是对象，提取CN字段
			if cn, ok := msgObj["CN"].(string); ok {
				msgStr = cn
			} else {
				msgStr = "冻结卡片失败"
			}
		} else if msg, ok := response["msg"].(string); ok {
			// msg是字符串
			msgStr = msg
		} else {
			msgStr = "冻结卡片失败"
		}
		return nil, NewPlatformError(h.platformID, "API_ERROR", msgStr, "冻结卡片失败")
	}

	// 返回统一格式的响应
	freezeResponse := &common.FreezeCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: response["data"],
	}

	return freezeResponse, nil
}

// HandleEnableCard 处理卡片解冻请求
func (h *PhotonPayAdapterHandler) HandleEnableCard(ctx context.Context, req *common.EnableCardRequest) (*common.EnableCardResponse, error) {
	// PhotonPay的解冻逻辑
	// 这里需要根据实际情况实现
	response := &common.EnableCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: nil,
	}

	return response, nil
}

// HandleCancelCard 处理卡片注销请求
func (h *PhotonPayAdapterHandler) HandleCancelCard(ctx context.Context, req *common.CancelCardRequest) (*common.CancelCardResponse, error) {
	// 构建PhotonPay注销请求
	cancelRequest := map[string]interface{}{
		"cardId": req.CardID,
	}

	// 序列化请求体
	bodyBytes, err := json.Marshal(cancelRequest)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "JSON_ERROR", "序列化请求失败", err.Error())
	}

	// 调用PhotonPay注销服务
	result, err := photonpayServices.CancelCard(ctx, h.client, bodyBytes)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "注销卡片失败", err.Error())
	}

	// 解析PhotonPay响应
	var response map[string]interface{}
	if err := json.Unmarshal(result, &response); err != nil {
		return nil, NewPlatformError(h.platformID, "PARSE_ERROR", "解析注销响应失败", err.Error())
	}

	// 检查响应状态
	if code, ok := response["code"].(string); !ok || code != "0000" {
		msg := "注销卡片失败"
		if m, ok := response["msg"].(string); ok {
			msg = m
		}
		return nil, NewPlatformError(h.platformID, "API_ERROR", msg, "注销卡片失败")
	}

	// 返回统一格式的响应
	cancelResponse := &common.CancelCardResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: response["data"],
	}

	return cancelResponse, nil
}

// HandleTransactionList 处理交易列表查询请求
func (h *PhotonPayAdapterHandler) HandleTransactionList(ctx context.Context, req *common.TransactionListRequest) (*common.TransactionListResponse, error) {
	// 从上下文中获取matrixAccount信息
	var matrixAccount string
	if matrixInfo := ctx.Value("matrix_account_info"); matrixInfo != nil {
		if matrixAccountInfo, ok := matrixInfo.(*models.UserMatrixAccount); ok {
			matrixAccount = matrixAccountInfo.MatrixAccount
		}
	}

	if matrixAccount == "" {
		return nil, NewPlatformError(h.platformID, "MISSING_PARAMETER", "缺少matrixAccount参数", "查询交易列表需要matrixAccount")
	}

	// 构建PhotonPay查询参数
	params := photonpayModels.VccTradeOrderQueryParams{
		PageIndex:      req.PageIndex,
		PageSize:       req.PageSize,
		MatrixAccount:  matrixAccount,
		CardID:         req.CardID,
		CreatedAtStart: req.BeginTime,
		CreatedAtEnd:   req.EndTime,
	}

	// 调用PhotonPay交易查询服务
	result, err := photonpayServices.GetVccTradeOrderList(ctx, h.client, params)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取交易列表失败", err.Error())
	}

	// 转换为统一格式
	transactions := make([]common.TransactionInfo, 0, len(result.Data))
	for _, row := range result.Data {
		transaction := common.TransactionInfo{
			TransactionID:       row.TransactionID,
			CardID:              row.CardID,
			CardNo:              row.MaskCardNo, // PhotonPay返回掩码卡号
			TransactionType:     row.TransactionType,
			Currency:            row.CardCurrency,
			Amount:              row.TransactionAmount,
			TransactionAmount:   row.TransactionAmount,
			TransactionCurrency: row.TransactionCurrency,
			Fee:                 0, // PhotonPay没有单独的手续费字段
			Status:              row.Status,
			TransactionTime:     row.CreatedAt,
			Detail:              row.MerchantNameLocation,
			Remark:              row.Msg,
			CreateTime:          row.CreatedAt,
		}

		transactions = append(transactions, transaction)
	}

	// 返回统一格式的响应
	transactionResponse := &common.TransactionListResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data:      transactions,
		PageIndex: result.PageIndex,
		PageSize:  result.PageSize,
		Total:     result.Total,
	}

	return transactionResponse, nil
}

// HandleTransactionDetail 处理交易详情查询请求
func (h *PhotonPayAdapterHandler) HandleTransactionDetail(ctx context.Context, req *common.TransactionDetailRequest) (*common.TransactionDetailResponse, error) {
	// 从上下文中获取matrixAccount信息
	var matrixAccount string
	if matrixInfo := ctx.Value("matrix_account_info"); matrixInfo != nil {
		if matrixAccountInfo, ok := matrixInfo.(*models.UserMatrixAccount); ok {
			matrixAccount = matrixAccountInfo.MatrixAccount
		}
	}

	if matrixAccount == "" {
		return nil, NewPlatformError(h.platformID, "MISSING_PARAMETER", "缺少matrixAccount参数", "查询交易详情需要matrixAccount")
	}

	// 构建PhotonPay查询参数
	params := photonpayModels.VccTradeOrderQueryParams{
		PageIndex:     1,
		PageSize:      1,
		MatrixAccount: matrixAccount,
		TransactionID: req.TransactionID,
	}

	// 调用PhotonPay交易查询服务
	result, err := photonpayServices.GetVccTradeOrderList(ctx, h.client, params)
	if err != nil {
		return nil, NewPlatformError(h.platformID, "API_CALL_ERROR", "获取交易详情失败", err.Error())
	}

	if len(result.Data) == 0 {
		return nil, NewPlatformError(h.platformID, "NOT_FOUND", "交易记录不存在", "未找到指定的交易记录")
	}

	row := result.Data[0]
	transaction := common.TransactionInfo{
		TransactionID:       row.TransactionID,
		CardID:              row.CardID,
		CardNo:              row.MaskCardNo,
		TransactionType:     row.TransactionType,
		Currency:            row.CardCurrency,
		Amount:              row.TransactionAmount,
		TransactionAmount:   row.TransactionAmount,
		TransactionCurrency: row.TransactionCurrency,
		Fee:                 0,
		Status:              row.Status,
		TransactionTime:     row.CreatedAt,
		Detail:              row.MerchantNameLocation,
		Remark:              row.Msg,
		CreateTime:          row.CreatedAt,
	}

	// 返回统一格式的响应
	transactionResponse := &common.TransactionDetailResponse{
		BaseResponse: common.BaseResponse{
			Code: "0000",
			Msg:  "success",
		},
		Data: transaction,
	}

	return transactionResponse, nil
}

func getStringOrDefault(value string, defaultValue string) string {
	if value == "" {
		return defaultValue
	}
	return value
}
